diff --git a/.dumi/loading.tsx b/.dumi/loading.tsx new file mode 100644 index 0000000..086748a --- /dev/null +++ b/.dumi/loading.tsx @@ -0,0 +1,5 @@ +import React from 'react'; + +export default () => { + return
客官,您慢点儿...
; +}; diff --git a/.dumi/tsconfig.json b/.dumi/tsconfig.json new file mode 100644 index 0000000..a32dd4f --- /dev/null +++ b/.dumi/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../tsconfig.json", + "include": ["**/*"] +} diff --git a/.dumirc.ts b/.dumirc.ts index 8ed82c5..24c93a8 100644 --- a/.dumirc.ts +++ b/.dumirc.ts @@ -6,7 +6,10 @@ export default defineConfig({ favicons: ['/logo.jpg'], history: { type: 'hash' }, themeConfig: { - name: 'zhst前端库', + name: 'lambo', + socialLinks: { + gitlab: 'http://10.0.0.88/web-project/zhst-component', + }, }, alias: { '@zhst/hooks': path.join(__dirname, 'packages/hooks/src'), diff --git a/.stylelintrc b/.stylelintrc index e362194..23164e7 100644 --- a/.stylelintrc +++ b/.stylelintrc @@ -1,3 +1,6 @@ { - "extends": "@umijs/lint/dist/config/stylelint" + "extends": "@umijs/lint/dist/config/stylelint", + "rules": { + "selector-class-pattern": null + } } diff --git a/.vscode/settings.json b/.vscode/settings.json index b9685e3..169b84f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,6 +3,9 @@ "ahooks", "antd", "COMPATER", + "flvjs", + "remuxer", + "transmuxer", "zhst" ] } diff --git a/docs/index.md b/docs/index.md index 89c3fc3..8973543 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,7 +1,7 @@ --- hero: - title: zhst - description: 前端工具库合集 + title: lambo + description: 致力于提升前端开发效率与规范 actions: - text: 快速上手 link: /bizs @@ -16,8 +16,23 @@ features: emoji: 🌈 description: 常用函数库 - title: meta - emoji: 🧸 + emoji: ☀️ description: 原子组件库 + - title: constants + emoji: 🈶️ + description: 静态定义库 + - title: request + emoji: 🥣 + description: 网络请求库 + - title: types + emoji: 🈸 + description: typescript 声明库 + - title: material + emoji: 🥱 + description: 物料库 + - title: cli + emoji: 🐔 + description: 脚手架 --- ## 目录结构 @@ -70,6 +85,10 @@ features: material 物料库 +
  • + cli + 脚手架 +
  • @@ -95,7 +114,7 @@ features: ## 本文档食用说明 -目前在开发中的项目为:@zhst/bizs、@zhst/hooks、@zhst/meta、@zhst/func。 +目前在进行中的项目为:@zhst/bizs、@zhst/hooks、@zhst/meta、@zhst/func.. bizs: 基于@zhst/hooks、@zhst/meta、@zhst/func 开发,基本贴近于业务。doing @@ -103,20 +122,20 @@ meta:基于 antd 开发,作为公司的定制化原子组件。doing< hooks:基于 ahooks、@zhst/func 定制化二次开发。doing -func:基于 lodash-es 定制化二次开发 (由于utils包名被使用了)doing +func:基于 lodash-es 定制化二次开发 (由于 utils 包名被使用了)doing ## 后续构思 想做一个,基于智慧视通开发场景和业务场景的前端技术流程化方案,希望它能渗透到整个研发的所有流程中。 -比如:代码规范、git提交规范、物料库、基于electron的前端工具客户端(可集成物料库、图片上传小工具)、api自动生成... +比如:代码规范、git 提交规范、物料库、基于 electron 的前端工具客户端(可集成物料库、图片上传小工具)、api 自动生成... :::info{title=@zhst/lint} -lint工具库,包含:eslint-config、eslint-plugin、commit-lint +lint 工具库,包含:eslint-config、eslint-plugin、commit-lint ::: :::info{title=@zhst/metarial} -物料库,可以直接通过 clone npm 仓库的形式生成模板页面 +物料库,可以直接通过 clone npm 仓库的形式生成模板页面,页面没有任何依赖,一个页面就是一个项目。 ::: :::info{title=@zhst/app} @@ -134,3 +153,7 @@ lint工具库,包含:eslint-config、eslint-plugin、commit-lint :::info{title=@zhst/constants} 静态变量枚举库 ::: + +:::info{title=@zhst/cli} +基于物料库的脚手架,可以直接通过可视化界面搭建项目,偏向于 lowcode+ 思维 +::: diff --git a/packages/biz/CHANGELOG.md b/packages/biz/CHANGELOG.md index 444b4f0..165ebe9 100644 --- a/packages/biz/CHANGELOG.md +++ b/packages/biz/CHANGELOG.md @@ -1,5 +1,18 @@ # @zhst/biz +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + +### Patch Changes + +- Updated dependencies + - @zhst/hooks@0.3.0 + - @zhst/func@0.3.0 + - @zhst/meta@0.3.0 + ## 0.2.4 ### Patch Changes diff --git a/packages/biz/es/BigImageModal/BigImageModal.d.ts b/packages/biz/es/BigImageModal/BigImageModal.d.ts new file mode 100644 index 0000000..05eab4a --- /dev/null +++ b/packages/biz/es/BigImageModal/BigImageModal.d.ts @@ -0,0 +1,23 @@ +import React from 'react'; +import type { ModalProps, DescriptionsProps, TabsProps } from 'antd'; +import './index.less'; +export declare const componentPrefix = "zhst-image"; +export interface BigImageModalProps extends ModalProps { + visible: boolean; + descriptionConfig: { + data: { + title: string; + children: Pick; + }[]; + }; + tabsConfig: { + data: Pick & { + key: 'NORMAL' | 'COMPATER' | 'TRACK'; + }; + }; + dataSource: any; + imageData: any; + relatedData: any; +} +declare const BigImageModal: React.FC; +export default BigImageModal; diff --git a/packages/biz/es/hooks/useTaskState/index.js b/packages/biz/es/BigImageModal/BigImageModal.js similarity index 67% rename from packages/biz/es/hooks/useTaskState/index.js rename to packages/biz/es/BigImageModal/BigImageModal.js index 3446bb4..5fe3e7b 100644 --- a/packages/biz/es/hooks/useTaskState/index.js +++ b/packages/biz/es/BigImageModal/BigImageModal.js @@ -1,153 +1,151 @@ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -import doRequest from "../../utils/request"; -import { NetworkType, useStores } from '@store/index'; -import { useMount, useUnmount } from '@zhst/hooks'; -import { useRef, useState } from 'react'; -var Streams = ['TASK_OVERVIEW_WAIT_START_STREAM', 'TASK_OVERVIEW_WAIT_STREAM', 'TASK_OVERVIEW_WAIT_START_SVINFER']; -var StreamsNum = [1, 2, 3]; -var RunsNum = [5, 9]; -var ErrorsNum = [7]; -var Runs = ['TASK_OVERVIEW_RUNNING', 'TASK_OVERVIEW_FINISH']; -var Errors = ['TASK_OVERVIEW_ERROR']; -export var getListTaskStatus = /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(data) { - var res; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return doRequest({ - url: '/singer.TaskManagerService/ListTaskStatusResponse', - method: 'POST', - data: data || {} - }); - case 2: - res = _context.sent; - return _context.abrupt("return", res); - case 4: - case "end": - return _context.stop(); - } - }, _callee); - })); - return function getListTaskStatus(_x) { - return _ref.apply(this, arguments); - }; -}(); -export var getCameraStatusFunc = function getCameraStatusFunc(list) { - var useNum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var _Runs = useNum ? RunsNum : Runs; - var _Errors = useNum ? ErrorsNum : Errors; - var _Streams = useNum ? StreamsNum : Streams; - var res = list.reduce(function (res, cur) { - var cameraId = cur.taskIndex.deviceId; - var status = cur.taskOverview; - res.some(function (ids, i) { - if (ids.includes(cameraId)) { - res[i] = ids.filter(function (id) { - return id !== cameraId; - }); - return true; - } - return false; - }); - if (_Runs.includes(status)) { - res[0].push(cameraId); - } else if (_Errors.includes(status)) { - res[1].push(cameraId); - } else if (_Streams.includes(status)) { - res[2].push(cameraId); - } - return res; - }, [[], [], []]); - return _toConsumableArray(res); +function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +// @ts-nocheck +import React, { useRef, useState } from 'react'; +import { Descriptions, Modal, Tabs } from 'antd'; +import classNames from 'classnames'; +import { get } from '@zhst/func'; +import "./index.less"; +import Navigation from "./components/navigation"; +var DescriptionsItem = Descriptions.Item; +export var componentPrefix = 'zhst-image'; +var initialStyle = { + fontSize: '12px' }; -var camerasStatusStoreList = [[], [], []]; -var num = 0; -var useTaskState = function useTaskState() { - var _useStores = useStores(), - store = _useStores.store; - var _useState = useState(camerasStatusStoreList), +var BigImageModal = function BigImageModal(props) { + var _props$title = props.title, + title = _props$title === void 0 ? '-' : _props$title, + open = props.open, + visible = props.visible, + children = props.children, + _props$descriptionCon = props.descriptionConfig, + descriptionConfig = _props$descriptionCon === void 0 ? { + data: [] + } : _props$descriptionCon, + _props$tabsConfig = props.tabsConfig, + tabsConfig = _props$tabsConfig === void 0 ? { + data: [{ + label: '对比图模式', + key: '1', + children: '对比图组件' + }, { + label: '场景图模式', + key: '2', + children: '场景图组件' + }] + } : _props$tabsConfig, + _props$dataSource = props.dataSource, + dataSource = _props$dataSource === void 0 ? [] : _props$dataSource, + _props$imageData = props.imageData, + imageData = _props$imageData === void 0 ? [] : _props$imageData, + _props$relatedData = props.relatedData, + relatedData = _props$relatedData === void 0 ? [] : _props$relatedData; + var showCropRef = useRef(false); + var scaleRef = useRef(0); + + // ========================== 头切换 ========================= + var _useState = useState(get(tabsConfig, 'data[0].key')), _useState2 = _slicedToArray(_useState, 2), - camerasStatusList = _useState2[0], - setCamerasStatusList = _useState2[1]; - var timerRef = useRef(null); - var getCameraStatus = function getCameraStatus(list) { - var useNum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var res = getCameraStatusFunc(list, useNum); - setCamerasStatusList(res); - }; - var request = function request(data) { - if (data) { - var list = []; - data.forEach(function (v) { - list.push.apply(list, _toConsumableArray(v.taskStatus)); - }); - getCameraStatus(list, store.networkType === NetworkType.NORMAL); - } - }; - useMount( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { - var res; - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - num++; - if (!(num - 1 > 0)) { - _context3.next = 3; - break; - } - return _context3.abrupt("return"); - case 3: - _context3.next = 5; - return getListTaskStatus(); - case 5: - res = _context3.sent; - getCameraStatus(res.taskStatus); - if (store.networkType === NetworkType.DUAL_NETWORK) { - timerRef.current = setInterval( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { - var res; - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return getListTaskStatus(); - case 2: - res = _context2.sent; - request([res]); - case 4: - case "end": - return _context2.stop(); - } - }, _callee2); - })), 2000); - } - case 8: - case "end": - return _context3.stop(); + activeKey = _useState2[0], + setActiveKey = _useState2[1]; + + // ========================= 预览切换下标 ========================= + var _useState3 = useState(0), + _useState4 = _slicedToArray(_useState3, 2), + previewIndex = _useState4[0], + setPreviewIndex = _useState4[1]; + var _useState5 = useState(false), + _useState6 = _slicedToArray(_useState5, 2), + isRelated = _useState6[0], + setIsRelated = _useState6[1]; + return /*#__PURE__*/React.createElement(Modal, _extends({ + destroyOnClose: true, + open: open || visible, + footer: null, + className: componentPrefix, + title: title + }, props), descriptionConfig.data.map(function (descriptions) { + var _descriptions$childre; + return /*#__PURE__*/React.createElement(Descriptions, { + key: descriptions.title, + title: /*#__PURE__*/React.createElement("p", { + style: { + margin: '12px 0 0', + fontSize: initialStyle.fontSize + } + }, descriptions.title), + column: 8, + style: { + padding: '0 64px' } - }, _callee3); - }))); - useUnmount(function () { - clearInterval(timerRef.current); - setCamerasStatusList([[], [], []]); - num--; - if (num === 0) { - camerasStatusStoreList = [[], [], []]; + }, descriptions === null || descriptions === void 0 || (_descriptions$childre = descriptions.children) === null || _descriptions$childre === void 0 ? void 0 : _descriptions$childre.map(function (item) { + return /*#__PURE__*/React.createElement(DescriptionsItem, { + key: item.key, + label: item.label, + span: 1, + contentStyle: { + fontSize: initialStyle.fontSize + }, + labelStyle: { + fontSize: initialStyle.fontSize + } + }, item.children); + })); + }), /*#__PURE__*/React.createElement(Tabs, _extends({ + defaultActiveKey: activeKey, + centered: true, + tabBarStyle: { + fontSize: '18px' + }, + items: tabsConfig.data + }, tabsConfig)), /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentPrefix, "-view-container")), + style: activeKey === 'TRACK' ? { + height: '718px', + marginBottom: '0px' + } : {} + }, activeKey !== 'TRACK' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Navigation, { + className: classNames("".concat(componentPrefix, "-view-container__nav"), previewIndex <= 0 && "".concat(componentPrefix, "-view-container__nav--disabled"), "".concat(componentPrefix, "-view-container__nav--left")), + show: isRelated ? imageData.length > 1 : dataSource.length > 1, + disabled: previewIndex <= 0, + prev: true, + onClick: function onClick() { + setPreviewIndex(function (pre) { + return pre - 1; + }); } - }); - return camerasStatusList; + }), /*#__PURE__*/React.createElement(Navigation, { + className: classNames("".concat(componentPrefix, "-view-container__nav"), (previewIndex >= imageData.length - 1 || previewIndex >= dataSource.length - 1) && "".concat(componentPrefix, "-view-container__nav--disabled"), "".concat(componentPrefix, "-view-container__nav--right")), + show: isRelated ? imageData.length > 1 : dataSource.length > 1, + disabled: previewIndex >= imageData.length - 1 || previewIndex >= dataSource.length - 1, + next: true, + onClick: /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(e) { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + setPreviewIndex(function (pre) { + return pre + 1; + }); + case 1: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }() + })))); }; -export default useTaskState; \ No newline at end of file +export default BigImageModal; \ No newline at end of file diff --git a/packages/biz/es/BigImageModal/components/navigation/index.d.ts b/packages/biz/es/BigImageModal/components/navigation/index.d.ts new file mode 100644 index 0000000..78b1ca8 --- /dev/null +++ b/packages/biz/es/BigImageModal/components/navigation/index.d.ts @@ -0,0 +1,13 @@ +import * as React from 'react'; +import './index.less'; +declare const Navigation: React.FC<{ + show?: boolean; + onClick?: React.MouseEventHandler; + prev?: boolean; + next?: boolean; + disabled?: boolean; + className?: string; + color?: string; + hoverColor?: string; +}>; +export default Navigation; diff --git a/packages/biz/es/BigImageModal/index.d.ts b/packages/biz/es/BigImageModal/index.d.ts new file mode 100644 index 0000000..bb07714 --- /dev/null +++ b/packages/biz/es/BigImageModal/index.d.ts @@ -0,0 +1,3 @@ +import BigImageModal from "./BigImageModal"; +export type { BigImageModalProps } from './BigImageModal'; +export default BigImageModal; diff --git a/packages/biz/es/BigImageModal/index.js b/packages/biz/es/BigImageModal/index.js index 5fe3e7b..417a89d 100644 --- a/packages/biz/es/BigImageModal/index.js +++ b/packages/biz/es/BigImageModal/index.js @@ -1,151 +1,2 @@ -function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -// @ts-nocheck -import React, { useRef, useState } from 'react'; -import { Descriptions, Modal, Tabs } from 'antd'; -import classNames from 'classnames'; -import { get } from '@zhst/func'; -import "./index.less"; -import Navigation from "./components/navigation"; -var DescriptionsItem = Descriptions.Item; -export var componentPrefix = 'zhst-image'; -var initialStyle = { - fontSize: '12px' -}; -var BigImageModal = function BigImageModal(props) { - var _props$title = props.title, - title = _props$title === void 0 ? '-' : _props$title, - open = props.open, - visible = props.visible, - children = props.children, - _props$descriptionCon = props.descriptionConfig, - descriptionConfig = _props$descriptionCon === void 0 ? { - data: [] - } : _props$descriptionCon, - _props$tabsConfig = props.tabsConfig, - tabsConfig = _props$tabsConfig === void 0 ? { - data: [{ - label: '对比图模式', - key: '1', - children: '对比图组件' - }, { - label: '场景图模式', - key: '2', - children: '场景图组件' - }] - } : _props$tabsConfig, - _props$dataSource = props.dataSource, - dataSource = _props$dataSource === void 0 ? [] : _props$dataSource, - _props$imageData = props.imageData, - imageData = _props$imageData === void 0 ? [] : _props$imageData, - _props$relatedData = props.relatedData, - relatedData = _props$relatedData === void 0 ? [] : _props$relatedData; - var showCropRef = useRef(false); - var scaleRef = useRef(0); - - // ========================== 头切换 ========================= - var _useState = useState(get(tabsConfig, 'data[0].key')), - _useState2 = _slicedToArray(_useState, 2), - activeKey = _useState2[0], - setActiveKey = _useState2[1]; - - // ========================= 预览切换下标 ========================= - var _useState3 = useState(0), - _useState4 = _slicedToArray(_useState3, 2), - previewIndex = _useState4[0], - setPreviewIndex = _useState4[1]; - var _useState5 = useState(false), - _useState6 = _slicedToArray(_useState5, 2), - isRelated = _useState6[0], - setIsRelated = _useState6[1]; - return /*#__PURE__*/React.createElement(Modal, _extends({ - destroyOnClose: true, - open: open || visible, - footer: null, - className: componentPrefix, - title: title - }, props), descriptionConfig.data.map(function (descriptions) { - var _descriptions$childre; - return /*#__PURE__*/React.createElement(Descriptions, { - key: descriptions.title, - title: /*#__PURE__*/React.createElement("p", { - style: { - margin: '12px 0 0', - fontSize: initialStyle.fontSize - } - }, descriptions.title), - column: 8, - style: { - padding: '0 64px' - } - }, descriptions === null || descriptions === void 0 || (_descriptions$childre = descriptions.children) === null || _descriptions$childre === void 0 ? void 0 : _descriptions$childre.map(function (item) { - return /*#__PURE__*/React.createElement(DescriptionsItem, { - key: item.key, - label: item.label, - span: 1, - contentStyle: { - fontSize: initialStyle.fontSize - }, - labelStyle: { - fontSize: initialStyle.fontSize - } - }, item.children); - })); - }), /*#__PURE__*/React.createElement(Tabs, _extends({ - defaultActiveKey: activeKey, - centered: true, - tabBarStyle: { - fontSize: '18px' - }, - items: tabsConfig.data - }, tabsConfig)), /*#__PURE__*/React.createElement("div", { - className: classNames("".concat(componentPrefix, "-view-container")), - style: activeKey === 'TRACK' ? { - height: '718px', - marginBottom: '0px' - } : {} - }, activeKey !== 'TRACK' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Navigation, { - className: classNames("".concat(componentPrefix, "-view-container__nav"), previewIndex <= 0 && "".concat(componentPrefix, "-view-container__nav--disabled"), "".concat(componentPrefix, "-view-container__nav--left")), - show: isRelated ? imageData.length > 1 : dataSource.length > 1, - disabled: previewIndex <= 0, - prev: true, - onClick: function onClick() { - setPreviewIndex(function (pre) { - return pre - 1; - }); - } - }), /*#__PURE__*/React.createElement(Navigation, { - className: classNames("".concat(componentPrefix, "-view-container__nav"), (previewIndex >= imageData.length - 1 || previewIndex >= dataSource.length - 1) && "".concat(componentPrefix, "-view-container__nav--disabled"), "".concat(componentPrefix, "-view-container__nav--right")), - show: isRelated ? imageData.length > 1 : dataSource.length > 1, - disabled: previewIndex >= imageData.length - 1 || previewIndex >= dataSource.length - 1, - next: true, - onClick: /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(e) { - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - setPreviewIndex(function (pre) { - return pre + 1; - }); - case 1: - case "end": - return _context.stop(); - } - }, _callee); - })); - return function (_x) { - return _ref.apply(this, arguments); - }; - }() - })))); -}; +import BigImageModal from "./BigImageModal"; export default BigImageModal; \ No newline at end of file diff --git a/packages/biz/es/BigImageModal/index.less b/packages/biz/es/BigImageModal/index.less index b26c6c8..966b5d6 100644 --- a/packages/biz/es/BigImageModal/index.less +++ b/packages/biz/es/BigImageModal/index.less @@ -1,5 +1,4 @@ .zhst-image { - .zhst-dialog-content { box-shadow: 0 4px 12px rgb(0 0 0 / 20%); } @@ -67,256 +66,7 @@ margin-bottom: 24px; } } -.zhst-image__img-view { - position: relative; - width: calc(100% - 46px - 46px - 20px - 20px); - height: 100%; - margin: 0 66px; - &-opt { - position: absolute; - z-index: 99; - top: 0; - } - - &-crop-opt { - position: absolute; - z-index: 99; - top: 0; - right: 0; - } - - &-align { - position: absolute; - top: 0; - left: 0; - pointer-events: none; - } - - &-main { - // height: 532px; - width: 100%; - height: 100%; - - &--cursor { - & canvas { - cursor: pointer !important; - } - } - } - - &-screenshot { - position: absolute; - z-index: 10; - } - - &-attach { - position: absolute; - z-index: 11; - bottom: 0; - - // left: 78px; - left: 0; - min-width: 120px; - height: 202px; - transition: all 200ms; - - &--fixed { - width: 152px !important; - background-color: #fff; - } - - &--zoomin { - height: 532px; - - &--fixed { - width: 398px !important; - } - } - - &__tab { - position: absolute; - top: 0; - left: 0; - display: flex; - - &-item { - display: flex; - width: 30px; - height: 24px; - align-items: center; - justify-content: center; - background: #000; - color: #fff; - cursor: pointer; - font-size: 12px; - opacity: 0.5; - transition: all 200ms; - - &--select { - width: 48px; - height: 34px; - background: #09f; - opacity: 1; - } - } - } - - &__scale { - position: absolute; - top: 4px; - right: 4px; - display: flex; - width: 30px; - height: 30px; - align-items: center; - justify-content: center; - background: rgb(0 0 0 / 60%); - border-radius: 100%; - cursor: pointer; - line-height: 30px; - text-align: center; - } - - &__img { - height: 100%; - object-fit: contain; - - &--fixed { - width: 100%; - object-fit: contain; - } - } - } -} - -.zhst-image__video-view { - position: relative; - overflow: hidden; - width: 100%; - height: 532px; - background-color: #333; - - // &-flv { - // width: 85%; - // } - &-screenshot { - position: absolute; - z-index: 10; - } - - &-crop-container { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - } - - &-align { - position: absolute; - top: 0; - left: 0; - pointer-events: none; - } - - &-opt { - position: absolute; - z-index: 99; - bottom: 0; - display: flex; - width: 100%; - height: 32px; - box-sizing: border-box; - align-items: center; - padding: 0 12px; - background-color: rgb(0 0 0 / 80%); - line-height: 32px; - - &>div:first-child { - display: flex; - align-items: center; - margin-right: 12px; - } - - &>div:last-child { - display: flex; - align-items: center; - margin-left: 12px; - } - - &-range { - display: flex; - height: 32px; - flex: 1; - align-items: center; - line-height: 32px; - text-align: center; - - &>div:first-child { - flex: 1; - } - - &>div:last-child { - width: 100px; - margin-left: 8px; - color: #fff; - } - } - } - - &__player-mask { - position: absolute; - z-index: 99; - top: 0; - right: 0; - bottom: 0; - left: 0; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - background-color: rgb(4 4 4 / 70%); - - &--bg { - z-index: 999; - background-color: rgb(4 4 4 / 100%); - } - - i { - cursor: pointer; - } - - &-title { - margin-top: 12px; - color: #fff; - text-align: center; - - & a { - color: #09f; - cursor: pointer; - text-decoration: underline; - } - } - } - - &__icon-wraper { - display: flex; - width: 80px; - height: 80px; - align-items: center; - justify-content: center; - background-color: rgb(255 255 255 / 10%); - border-radius: 50%; - cursor: pointer; - line-height: 80px; - text-align: center; - - // &:hover { - // background: #0099ff; - // } - } -} .zhst-image__tool { display: flex; @@ -504,7 +254,6 @@ display: flex; width: 100%; justify-content: center; - border-color: #f0f0f0; border-bottom-width: 1px; border-bottom-style: solid; @@ -553,57 +302,6 @@ } } -.zhst-image__btn-group { - // display: flex; - width: 30px; - box-shadow: 0 2px 6px 0 rgb(0 0 0 / 40%); - - &__item { - display: flex; - width: 30px; - height: 30px; - align-items: center; - justify-content: center; - background: #000; - - &>button { - padding: 0; - color: #fff; - - &:hover { - color: #09f; - } - - &:active { - color: #09f; - } - - &:focus { - color: #fff; - } - - &>span { - display: flex; - } - } - - &--active { - &>button { - color: #09f; - } - } - } - - &--circle { - background-color: none; - box-shadow: none; - } - - &--circle &__item { - margin-bottom: 4px; - border-radius: 50%; - } -} .zhst-image__compater-view { display: flex; @@ -962,78 +660,6 @@ } } -.zhst-image__score { - display: flex; - flex-direction: column; - align-items: center; - - &-box { - position: relative; - display: flex; - box-sizing: border-box; - align-items: center; - justify-content: center; - margin-bottom: 12px; - border-radius: 50%; - - &-bg { - display: flex; - overflow: hidden; - box-sizing: border-box; - align-items: flex-end; - justify-content: center; - border: 2px solid #fff; - background-color: #fff; - border-radius: 50%; - - &-inner { - width: 100% !important; - height: 0; - } - } - } - - &-score { - position: absolute; - top: 50%; - left: 50%; - color: rgb(0 0 0 / 88%); - font-size: 28px; - transform: translate(-50%, -50%); - } - - &-text { - width: 54px; - height: 24px; - color: rgb(0 0 0 / 88%); - font-size: 18px; - line-height: 24px; - } -} - -.zhst-image__CornerScore { - position: absolute; - right: 0; - bottom: 0; - width: 56px; - height: 22px; - line-height: 22px; - text-align: right; - vertical-align: bottom; - padding-right: 1px; - background-size: 100%; - background-image: url('./images/percent_background.png'); - z-index: 99; - - &>span { - padding-right: 6px; - line-height: 22px; - font-size: 12px; - vertical-align: middle; - color: rgba(255, 255, 255, 1); - } -} - .zhst-image__attributePanel { margin: 0 66px; background: #f6f6f6; @@ -1082,7 +708,6 @@ .relatedContent { width: 100%; height: 100px; - display: flex; .relatedPics { @@ -1108,19 +733,19 @@ } .disabled { - color: rgba(0, 0, 0, 0.25); + color: rgba(0, 0, 0, 25%); } .relatedBtn { flex: 1; font-size: 14px; - color: #333333; + color: #333; display: flex; align-items: flex-end; cursor: pointer; &:hover { - color: #0099ff; + color: #09f; } } } diff --git a/packages/biz/es/BigImageModal/index.temp.js b/packages/biz/es/BigImageModal/index.temp.js deleted file mode 100644 index 227915b..0000000 --- a/packages/biz/es/BigImageModal/index.temp.js +++ /dev/null @@ -1,789 +0,0 @@ -function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } -function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } -function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -// @ts-nocheck -import React, { useEffect, useRef, useState, useMemo } from 'react'; -import { useLatest, useThrottleFn } from 'ahooks'; -import { isFunction, pick, noop, get, isEmpty } from 'lodash-es'; -import classNames from 'classnames'; -import { message, Modal, Tabs as TabPane } from 'antd'; -import KeyCode from 'rc-util/lib/KeyCode'; -import { observer } from 'mobx-react-lite'; -import ImgView from "./ImgView"; -import VideoView from "./VideoView"; -import CompareView from "./CompareView"; -import Tool from "./Tool"; -import Header, { Tabs } from "./Header"; -import Navigation from "./Nav"; -import AttributePanel from "./AttributePanel"; -import { usePropState, cssPrefix, getSolt } from "./utils"; -import { screenshotButtonProp } from "../adapter/BigImageModalAdapter/interface"; -import NullView from "./NullDialog"; -import styles from "./index.module.scss"; -import { generateImg } from '@common/utils'; -import IconFont from "../iconfont/IconFont"; -import addEventListenerWrap from '@common/utils/addEventListener'; -import Carousel from "./Carousel"; -import { doubleClick } from '@common/components/doubleCheck'; -import { store } from '@store/index'; -import { store as achieveStore } from '@pages/archive/store'; -var componentName = cssPrefix; -//查看对比图和场景图组件 -var BigImageDialog = function BigImageDialog(props) { - var _props$hasPre = props.hasPre, - propHasPre = _props$hasPre === void 0 ? false : _props$hasPre, - _props$hasNext = props.hasNext, - propHasNext = _props$hasNext === void 0 ? false : _props$hasNext, - _props$loadNext = props.loadNext, - loadNext = _props$loadNext === void 0 ? noop : _props$loadNext, - _props$loadPre = props.loadPre, - loadPre = _props$loadPre === void 0 ? noop : _props$loadPre, - _props$visible = props.visible, - visible = _props$visible === void 0 ? true : _props$visible, - onClose = props.onClose, - _props$isLoading = props.isLoading, - propIsLoading = _props$isLoading === void 0 ? false : _props$isLoading, - _props$selectIndex = props.selectIndex, - propSelectIndex = _props$selectIndex === void 0 ? 0 : _props$selectIndex, - onSelectIndexChange = props.onSelectIndexChange, - _props$dataSource = props.dataSource, - dataSource = _props$dataSource === void 0 ? [] : _props$dataSource, - _props$relatedData = props.relatedData, - relatedData = _props$relatedData === void 0 ? [] : _props$relatedData, - screenshotButtonRender = props.screenshotButtonRender, - transformPropFunc = props.transformPropFunc, - transformVideoPropFunc = props.transformVideoPropFunc, - _props$defaultModel = props.defaultModel, - defaultModel = _props$defaultModel === void 0 ? 'IMAGE' : _props$defaultModel, - otherImgViewProp = props.imgViewProp, - otherVideoViewProp = props.videoViewProp, - otherCarouselProp = props.carouselProp, - otherToolProp = props.ToolProps, - _props$showTool = props.showTool, - showTool = _props$showTool === void 0 ? true : _props$showTool, - children = props.children, - nullDialogProp = props.nullDialogProp, - _props$showHeader = props.showHeader, - showHeader = _props$showHeader === void 0 ? true : _props$showHeader, - _props$tabsFilter = props.tabsFilter, - tabsFilter = _props$tabsFilter === void 0 ? ['COMPATER', 'NORMAL'] : _props$tabsFilter, - useVirtual = props.useVirtual, - _props$title = props.title, - title = _props$title === void 0 ? '查看大图' : _props$title, - _props$specialTitle = props.specialTitle, - specialTitle = _props$specialTitle === void 0 ? '' : _props$specialTitle, - _props$showCarousel = props.showCarousel, - showCarousel = _props$showCarousel === void 0 ? true : _props$showCarousel, - _props$isRelated = props.isRelated, - isRelated = _props$isRelated === void 0 ? false : _props$isRelated; - console.log('props', props); - //可观测值 - var showCrop$Ref = useRef(false); - var scale$Ref = useRef(0); - var showCrop$ = showCrop$Ref.current; - var scale$ = scale$Ref.current; - // ========================== 头切换 ========================= - var _useState = useState(tabsFilter.length > 1 ? Object.keys(Tabs)[0] : Object.keys(Tabs)[1]), - _useState2 = _slicedToArray(_useState, 2), - tab = _useState2[0], - setTab = _useState2[1]; - var _useState3 = useState('related'), - _useState4 = _slicedToArray(_useState3, 2), - activeKey = _useState4[0], - setActiveKey = _useState4[1]; - var _useState5 = useState(dataSource), - _useState6 = _slicedToArray(_useState5, 2), - similarList = _useState6[0], - setSimilarList = _useState6[1]; // 其他相似目标列表 - var _useState7 = useState(relatedData), - _useState8 = _slicedToArray(_useState7, 2), - relatedList = _useState8[0], - setRelatedList = _useState8[1]; // 已关联列表 - var _useState9 = useState(dataSource), - _useState10 = _slicedToArray(_useState9, 2), - imageData = _useState10[0], - setImageData = _useState10[1]; // 其他相似目标列表 - var lastSimData = useLatest(similarList); - var lastRelatedData = useLatest(relatedList); - - // ========================== 内部转换 ========================= - var _useState11 = useState(defaultModel), - _useState12 = _slicedToArray(_useState11, 2), - model = _useState12[0], - setModel = _useState12[1]; // 图片/视频模式 - useEffect(function () { - if (activeKey === 'unRlated') { - setImageData(lastSimData.current); - setSelectIndex(0); - } - if (activeKey === 'related') { - setImageData(lastRelatedData.current); - setSelectIndex(0); - } - }, [activeKey]); - useEffect(function () { - setSimilarList(dataSource); - if (activeKey === 'unRelated') { - setImageData(dataSource); - } - }, [dataSource]); - var carouseDataSource = useMemo(function () { - return imageData.map(function (v, index) { - return { - url: generateImg(get(v, 'passerbyImage.objectRects.0.fileKey')), - key: index, - passerbyId: get(v, 'passerbyId') - }; - }); - }, [imageData, dataSource]); - - //选择 - var _usePropState = usePropState(propSelectIndex), - _usePropState2 = _slicedToArray(_usePropState, 2), - selectIndex = _usePropState2[0], - setSelectIndex = _usePropState2[1]; - var hasPre = propHasPre ? true : selectIndex > 0; - var changeIndex = isRelated ? imageData.length - 1 : dataSource.length - 1; - var hasNext = propHasNext ? true : selectIndex < changeIndex; - //设置选中 - var latestSelectIndex = useLatest(selectIndex); - var latestDataSource = isRelated ? useLatest(imageData) : useLatest(dataSource); - //加一个防背推 - var seq = useRef(0); - var _useThrottleFn = useThrottleFn( /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(arg) { - var _seq, selectIndex, dataSource, newIndex; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _seq = ++seq.current; - selectIndex = latestSelectIndex.current; - dataSource = latestDataSource.current; - newIndex = isFunction(arg) ? arg(selectIndex) : arg; - if (!(newIndex > dataSource.length - 1)) { - _context.next = 11; - break; - } - if (!propHasNext) { - _context.next = 10; - break; - } - _context.next = 8; - return loadNext(newIndex); - case 8: - _context.next = 11; - break; - case 10: - newIndex = dataSource.length - 1; - case 11: - if (newIndex < 0) { - newIndex = 0; - } - if (!(_seq !== seq.current)) { - _context.next = 14; - break; - } - return _context.abrupt("return"); - case 14: - onSelectIndexChange && onSelectIndexChange(newIndex); - setSelectIndex(newIndex); - case 16: - case "end": - return _context.stop(); - } - }, _callee); - })); - return function (_x) { - return _ref.apply(this, arguments); - }; - }(), { - wait: 500 - }), - setSelectIndexWrapper = _useThrottleFn.run; - - //异步获取数据 - var _useState13 = useState(null), - _useState14 = _slicedToArray(_useState13, 2), - selectItem = _useState14[0], - setSelectItem = _useState14[1]; - var _useState15 = useState(true), - _useState16 = _slicedToArray(_useState15, 2), - isFetching = _useState16[0], - setIsFetching = _useState16[1]; - //人员属性 - var _useState17 = useState([]), - _useState18 = _slicedToArray(_useState17, 2), - attributeList = _useState18[0], - setAttributeList = _useState18[1]; - var isLoading = useMemo(function () { - return propIsLoading || isFetching; - }, [propIsLoading, isFetching]); - useEffect(function () { - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { - var data; - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - setIsFetching(true); - data = {}; - if (!isRelated) { - _context2.next = 8; - break; - } - _context2.next = 5; - return transformPropFunc(imageData[selectIndex]); - case 5: - data = _context2.sent; - _context2.next = 11; - break; - case 8: - _context2.next = 10; - return transformPropFunc(dataSource[selectIndex]); - case 10: - data = _context2.sent; - case 11: - setAttributeList(get(data, 'attributeList', [])); - //防背推 - if (selectIndex === latestSelectIndex.current) { - setSelectItem(data); - setIsFetching(false); - } - case 13: - case "end": - return _context2.stop(); - } - }, _callee2); - }))(); - }, [selectIndex, dataSource, imageData, isRelated]); - var selectqualityScore = useMemo(function () { - return get(selectItem, 'qualityScore'); - }, [selectItem]); - //支持视频url异步获取 - var _useState19 = useState(null), - _useState20 = _slicedToArray(_useState19, 2), - flvUrl = _useState20[0], - setFlvUrl = _useState20[1]; - var _useState21 = useState(null), - _useState22 = _slicedToArray(_useState21, 2), - maxDuration = _useState22[0], - setMaxDuration = _useState22[1]; - useEffect(function () { - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { - var _yield$transformVideo, _flvUrl, _maxDuration; - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - if (!(model === 'IMAGE')) { - _context3.next = 4; - break; - } - setFlvUrl(null); - setMaxDuration(null); - return _context3.abrupt("return"); - case 4: - if (!isFunction(transformVideoPropFunc)) { - _context3.next = 15; - break; - } - //先情空 - setFlvUrl(null); - setMaxDuration(null); - _context3.next = 9; - return transformVideoPropFunc(selectItem); - case 9: - _yield$transformVideo = _context3.sent; - _flvUrl = _yield$transformVideo.flvUrl; - _maxDuration = _yield$transformVideo.maxDuration; - //防背推 - if (selectIndex === latestSelectIndex.current) { - setMaxDuration(_maxDuration); - setFlvUrl(_flvUrl); - } - _context3.next = 17; - break; - case 15: - setFlvUrl(get(selectItem, 'flvUrl')); - setMaxDuration(get(selectItem, 'maxDuration')); - case 17: - case "end": - return _context3.stop(); - } - }, _callee3); - }))(); - }, [selectItem, model]); - - //切换选中index时候变更key 让组件走销毁逻辑 减少大图/视频组件内部逻辑复杂度 - var key = 0; - var imgCmpKey = useMemo(function () { - return "img-key-".concat(key); - }, [key]); - var videoCmpKey = useMemo(function () { - return "video-key-".concat(key); - }, [key]); - - // ========================== 分离参数 ========================= - var CompareViewProp = { - targertImg: generateImg(get(selectItem, 'imgSummary', '')), - // 对比图 - score: get(selectItem, 'score'), - similarScore: get(selectItem, 'similarScore'), - sourceImg: get(selectItem, 'constractKey', '') || get(selectItem, 'compaterImages.0') || generateImg(get(selectItem, 'imgSummary', '')), - compaterImages: get(selectItem, 'compaterImages', []), - specialTitle: specialTitle, - isRelated: isRelated - }; - var carouselProp = _objectSpread({ - selectIndex: selectIndex, - setSelectIndex: setSelectIndexWrapper, - hasPre: hasPre, - hasNext: hasNext, - dataSource: carouseDataSource - }, otherCarouselProp); - var imgViewProp = _objectSpread(_objectSpread(_objectSpread({}, pick(selectItem, ['imageKey', 'odRect', 'attachImg', 'score'])), {}, { - screenshotButtonRender: screenshotButtonRender - }, otherImgViewProp), {}, { - showCrop$: showCrop$, - scale$: scale$ - }); - var videoViewProp = _objectSpread(_objectSpread({ - flvUrl: flvUrl, - maxDuration: maxDuration, - screenshotButtonRender: screenshotButtonRender - }, otherVideoViewProp), {}, { - showCrop$: showCrop$ - }); - var ToolProps = _objectSpread(_objectSpread({}, otherToolProp), {}, { - isGray: true - }); - - // ========================== 插槽参数 ========================= - var imgViewRef = useRef(null); - var VideoViewRef = useRef(null); - scale$; - var param = { - tab: tab, - selectItem: selectItem, - imgViewRef: imgViewRef, - VideoViewRef: VideoViewRef, - model: model, - setModel: setModel, - showCrop$: showCrop$, - scale$: scale$ - }; - var slots = getSolt(children, param); - - // ========================== 监听键盘 ========================= - useEffect(function () { - var onKeyDown = function onKeyDown(event) { - var keyCode = event.keyCode; - if (keyCode === KeyCode.LEFT) { - setSelectIndexWrapper(function (pre) { - return --pre; - }); - } - if (keyCode === KeyCode.RIGHT) { - setSelectIndexWrapper(function (pre) { - return ++pre; - }); - } - }; - document.addEventListener('keydown', onKeyDown); - return function () { - document.removeEventListener('keydownm', onKeyDown); - }; - }, []); - - // ========================== 监听滚轮 ========================= - React.useEffect(function () { - var mousewheelListener = function mousewheelListener(e) { - e.preventDefault(); - var direction = 0; - if (e.wheelDelta) { - //IE/Opera/Chrome - if (e.wheelDelta > 0) { - //向上滚动事件 - direction = 1; - } else { - //向下滚动事件 - direction = -1; - } - } else if (e.detail) { - //Firefox - if (e.detail < 0) { - //向上滚动事件 - direction = 1; - } else { - //向下滚动事件 - direction = -1; - } - } - setSelectIndexWrapper(function (pre) { - return direction < 0 ? pre + 1 : pre - 1; - }); - }; - var handleMouseWheel; - if (store.bigImgScrollEmit) { - handleMouseWheel = addEventListenerWrap(document, 'mousewheel', mousewheelListener); - } else { - var _handleMouseWheel; - (_handleMouseWheel = handleMouseWheel) === null || _handleMouseWheel === void 0 || _handleMouseWheel.remove(); - } - return function () { - var _handleMouseWheel2; - (_handleMouseWheel2 = handleMouseWheel) === null || _handleMouseWheel2 === void 0 || _handleMouseWheel2.remove(); - }; - }, [store.bigImgScrollEmit]); - var tabList = [{ - key: 'related', - label: '关联的目标', - children: /*#__PURE__*/React.createElement("div", { - className: styles.relatedContent - }, showCarousel && /*#__PURE__*/React.createElement("div", { - className: classNames(styles.relatedPics) - }, /*#__PURE__*/React.createElement(Carousel, carouselProp)), /*#__PURE__*/React.createElement("div", { - style: isEmpty(relatedList) ? { - color: 'rgba(0, 0, 0, 0.25)', - cursor: 'not-allowed' - } : {}, - className: classNames(styles.relatedBtn), - onClick: /*#__PURE__*/function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(e) { - var archiveId, passerbyId; - return _regeneratorRuntime().wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - if (isEmpty(relatedList)) { - e.stopPropagation(); - } else { - try { - archiveId = selectItem.archiveId, passerbyId = selectItem.passerbyId; - if (archiveId && passerbyId) { - doubleClick({ - title: '确认取消关联,取消后可在“其他相似目标推荐”处再次关联', - checkboxLabel: '同时移除档案对应轨迹', - checked: true, - onOk: function () { - var _onOk = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { - var _yield$achieveStore$a, relatedPassersby, _yield$achieveStore$a2, similarPassersby; - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _context4.prev = 0; - _context4.next = 3; - return achieveStore.archive.UnLinkTarget(passerbyId, archiveId); - case 3: - message.success('目标已成功取消关联!'); - // 更新已关联目标列表 - _context4.next = 6; - return achieveStore.archive.GetRelatedArchive(archiveId); - case 6: - _yield$achieveStore$a = _context4.sent; - relatedPassersby = _yield$achieveStore$a.relatedPassersby; - setRelatedList(relatedPassersby); - setImageData(relatedPassersby); - // 更新当前相似目标列表 - _context4.next = 12; - return achieveStore.archive.GetSimilarPasserbyList(archiveId); - case 12: - _yield$achieveStore$a2 = _context4.sent; - similarPassersby = _yield$achieveStore$a2.similarPassersby; - setSimilarList(similarPassersby); - setSelectIndex(function (pre) { - if (pre > 0) { - return pre - 1; - } else { - return 0; - } - }); - _context4.next = 22; - break; - case 18: - _context4.prev = 18; - _context4.t0 = _context4["catch"](0); - message.success('目标取消关联失败!'); - console.error(_context4.t0); - case 22: - case "end": - return _context4.stop(); - } - }, _callee4, null, [[0, 18]]); - })); - function onOk() { - return _onOk.apply(this, arguments); - } - return onOk; - }() - }); - } - } catch (e) { - console.error(e); - } - } - case 1: - case "end": - return _context5.stop(); - } - }, _callee5); - })); - return function (_x2) { - return _ref4.apply(this, arguments); - }; - }() - }, /*#__PURE__*/React.createElement(IconFont, { - icon: "icon-guanlian", - styles: { - fontWeight: 'bold', - margin: '0px 4px 0px 17px' - }, - size: 16 - }), "\u53D6\u6D88\u5173\u8054")) - }, { - key: 'unRlated', - label: '其他相似目标推荐', - children: /*#__PURE__*/React.createElement("div", { - className: styles.relatedContent - }, showCarousel && /*#__PURE__*/React.createElement("div", { - className: classNames(styles.relatedPics) - }, /*#__PURE__*/React.createElement(Carousel, carouselProp)), /*#__PURE__*/React.createElement("div", { - style: isEmpty(lastSimData.current) ? { - color: 'rgba(0, 0, 0, 0.25)', - cursor: 'not-allowed' - } : {}, - className: classNames(styles.relatedBtn), - onClick: /*#__PURE__*/function () { - var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(e) { - var archiveId, passerbyId, archiveGroupId, trajectoryId, _yield$achieveStore$a3, similarPassersby, _yield$achieveStore$a4, relatedPassersby; - return _regeneratorRuntime().wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - if (!isEmpty(lastSimData.current)) { - _context6.next = 4; - break; - } - e.stopPropagation(); - _context6.next = 28; - break; - case 4: - _context6.prev = 4; - archiveId = selectItem.archiveId, passerbyId = selectItem.passerbyId, archiveGroupId = selectItem.archiveGroupId, trajectoryId = selectItem.trajectoryId; - if (!(archiveId && passerbyId && archiveGroupId && trajectoryId)) { - _context6.next = 22; - break; - } - _context6.next = 9; - return achieveStore.archive.LinkTarget({ - passerbyId: passerbyId, - archiveId: archiveId, - archiveGroupId: archiveGroupId, - trajectoryId: trajectoryId - }); - case 9: - message.success('目标已成功关联!'); - // 更新当前相似目标列表 - _context6.next = 12; - return achieveStore.archive.GetSimilarPasserbyList(archiveId); - case 12: - _yield$achieveStore$a3 = _context6.sent; - similarPassersby = _yield$achieveStore$a3.similarPassersby; - setSimilarList(similarPassersby); - setImageData(similarPassersby); - - // 更新已关联目标列表 - _context6.next = 18; - return achieveStore.archive.GetRelatedArchive(archiveId); - case 18: - _yield$achieveStore$a4 = _context6.sent; - relatedPassersby = _yield$achieveStore$a4.relatedPassersby; - setRelatedList(relatedPassersby); - setSelectIndex(function (pre) { - if (pre > 0) { - return pre - 1; - } else { - return 0; - } - }); - case 22: - _context6.next = 28; - break; - case 24: - _context6.prev = 24; - _context6.t0 = _context6["catch"](4); - message.error('目标关联失败!'); - console.error(_context6.t0); - case 28: - case "end": - return _context6.stop(); - } - }, _callee6, null, [[4, 24]]); - })); - return function (_x3) { - return _ref5.apply(this, arguments); - }; - }() - }, /*#__PURE__*/React.createElement(IconFont, { - icon: "icon-guanlian", - styles: { - fontWeight: 'bold', - margin: '0px 4px 0px 17px' - }, - size: 16 - }), "\u5173\u8054")) - }]; - return /*#__PURE__*/React.createElement(Modal, { - open: visible, - onCancel: onClose, - footer: null, - className: classNames(componentName), - centered: true, - title: title - }, !isEmpty(attributeList) && /*#__PURE__*/React.createElement(AttributePanel, { - attributeList: attributeList - }), showHeader && /*#__PURE__*/React.createElement(Header, { - noBgColor: !isEmpty(attributeList), - value: tab, - onChange: setTab, - tabsFilter: tabsFilter - }), /*#__PURE__*/React.createElement("div", { - className: classNames("".concat(componentName, "-view-container")), - style: tab === 'TRACK' ? { - height: '718px', - marginBottom: '0px' - } : {} - }, tab !== 'TRACK' && /*#__PURE__*/React.createElement(React.Fragment, null, model == 'IMAGE' && tab === 'COMPATER' && !isEmpty(selectItem) && /*#__PURE__*/React.createElement(CompareView, CompareViewProp), !isLoading && model == 'IMAGE' && tab === 'NORMAL' && !isEmpty(selectItem === null || selectItem === void 0 ? void 0 : selectItem.rectList) && /*#__PURE__*/React.createElement(ImgView, _extends({ - key: imgCmpKey - }, imgViewProp, { - ref: imgViewRef - })), !isLoading && model == 'IMAGE' && isEmpty(selectItem) && tab === 'COMPATER' && /*#__PURE__*/React.createElement(NullView, nullDialogProp), !isLoading && model == 'IMAGE' && isEmpty(selectItem.rectList) && tab === 'NORMAL' && /*#__PURE__*/React.createElement(NullView, { - emptyText: isRelated ? '暂无匹配数据' : '暂无数据' - }), !isLoading && model == 'VIDEO' && /*#__PURE__*/React.createElement(VideoView, _extends({ - key: videoCmpKey - }, videoViewProp, { - ref: VideoViewRef - })), /*#__PURE__*/React.createElement(Navigation, { - className: classNames("".concat(componentName, "-view-container__nav"), !hasPre && "".concat(componentName, "-view-container__nav--disabled"), "".concat(componentName, "-view-container__nav--left")), - show: isRelated ? imageData.length !== 1 : dataSource.length !== 1, - disabled: !hasPre, - prev: true, - onClick: function onClick(e) { - if (useVirtual && selectIndex === 0) { - !!loadPre && loadPre(); - //都跳转到第一个 - setSelectIndexWrapper(0); - } else { - setSelectIndexWrapper(function (pre) { - return pre - 1; - }); - } - } - }), /*#__PURE__*/React.createElement(Navigation, { - className: classNames("".concat(componentName, "-view-container__nav"), !hasNext && "".concat(componentName, "-view-container__nav--disabled"), "".concat(componentName, "-view-container__nav--right")), - show: isRelated ? imageData.length !== 1 : dataSource.length !== 1, - disabled: !hasNext, - next: true, - onClick: /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(e) { - return _regeneratorRuntime().wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - if (!isRelated) { - _context7.next = 12; - break; - } - if (!(useVirtual && selectIndex === imageData.length - 1)) { - _context7.next = 9; - break; - } - _context7.t0 = !!loadNext; - if (!_context7.t0) { - _context7.next = 6; - break; - } - _context7.next = 6; - return loadNext(); - case 6: - //都跳转到第一个 - setSelectIndexWrapper(0); - _context7.next = 10; - break; - case 9: - setSelectIndexWrapper(function (pre) { - return pre + 1; - }); - case 10: - _context7.next = 21; - break; - case 12: - if (!(useVirtual && selectIndex === dataSource.length - 1)) { - _context7.next = 20; - break; - } - _context7.t1 = !!loadNext; - if (!_context7.t1) { - _context7.next = 17; - break; - } - _context7.next = 17; - return loadNext(); - case 17: - //都跳转到第一个 - setSelectIndexWrapper(0); - _context7.next = 21; - break; - case 20: - setSelectIndexWrapper(function (pre) { - return pre + 1; - }); - case 21: - case "end": - return _context7.stop(); - } - }, _callee7); - })); - return function (_x4) { - return _ref6.apply(this, arguments); - }; - }() - }))), tab !== 'TRACK' && showTool && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { - className: classNames("".concat(componentName, "-tool-container")) - }, /*#__PURE__*/React.createElement(Tool, _extends({}, ToolProps, { - param: param - }))), slots['after-tool']), !!selectqualityScore && store.user.isfaceScore && model == 'IMAGE' && tab === 'NORMAL' && /*#__PURE__*/React.createElement("div", { - style: isRelated ? { - bottom: 220 - } : { - bottom: 90 - }, - slot: 'after-tool', - className: classNames("".concat(componentName, "__face-score")) - }, "\u4EBA\u8138\u8D28\u91CF\u5206\uFF1A".concat(selectqualityScore.toFixed(2))), isRelated && tab !== 'TRACK' && /*#__PURE__*/React.createElement("div", { - className: styles.relatedWrapper - }, /*#__PURE__*/React.createElement(TabPane, { - className: styles.relatedTabs, - tabPosition: 'left', - activeKey: activeKey, - onChange: function onChange(key) { - setActiveKey(key); - }, - items: tabList.map(function (item) { - return { - label: item.label, - key: item.key, - children: item.children - }; - }) - }))); -}; -export default observer(BigImageDialog); \ No newline at end of file diff --git a/packages/biz/es/BigImageModal/mock.d.ts b/packages/biz/es/BigImageModal/mock.d.ts new file mode 100644 index 0000000..257ed75 --- /dev/null +++ b/packages/biz/es/BigImageModal/mock.d.ts @@ -0,0 +1,294 @@ +export declare const IMAGE_DATA: { + enAbleDeleteFeature: boolean; + tabsFilter: string[]; + dataSources: { + objectId: string; + condition: { + featureInfo: null; + featureData: string; + imageData: string; + alg: string; + rect: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageUrl: string; + srcImageUrl: string; + }; + score: number; + timestamp: number; + deviceId: string; + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + objectIndex: { + objectId: string; + solutionId: string; + deviceId: string; + fragmentId: string; + }; + objectType: string; + isObjectTrack: boolean; + pathId: string; + frameInfo: { + frameId: string; + frameTimestamp: string; + width: number; + height: number; + originWidth: number; + originHeight: number; + offsetTime: string; + skipNumber: string; + }; + level: number; + bboxInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + bboxExtInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageKey: string; + objectExtImageKey: string; + frameImageKey: string; + confidence: number; + sourceObjectId: string; + storeTimestamp: string; + gbNumber: string; + qualityScore: number; + subObjectCount: number; + subObjectType: string[]; + subObjectIds: string[]; + cameraInfo: { + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + }; + solutionId: string; + fragmentId: string; + contrastKey: string; + compaterImages: string[]; + imgSummary: string; + imageKey: string; + srcImageUrl: string; + algorithmVersion: string; + cameraId: string; + cameraName: string; + }[]; + selectIndex: number; + disableBtn: number[]; + dataSource: { + objectId: string; + condition: { + featureInfo: null; + featureData: string; + imageData: string; + alg: string; + rect: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageUrl: string; + srcImageUrl: string; + }; + score: number; + timestamp: number; + deviceId: string; + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + objectIndex: { + objectId: string; + solutionId: string; + deviceId: string; + fragmentId: string; + }; + objectType: string; + isObjectTrack: boolean; + pathId: string; + frameInfo: { + frameId: string; + frameTimestamp: string; + width: number; + height: number; + originWidth: number; + originHeight: number; + offsetTime: string; + skipNumber: string; + }; + level: number; + bboxInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + bboxExtInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageKey: string; + objectExtImageKey: string; + frameImageKey: string; + confidence: number; + sourceObjectId: string; + storeTimestamp: string; + gbNumber: string; + qualityScore: number; + subObjectCount: number; + subObjectType: string[]; + subObjectIds: string[]; + cameraInfo: { + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + }; + solutionId: string; + fragmentId: string; + contrastKey: string; + compaterImages: string[]; + imgSummary: string; + imageKey: string; + srcImageUrl: string; + algorithmVersion: string; + cameraId: string; + cameraName: string; + }[]; + isArchiveDetail: boolean; + ToolProps: { + renderVideoBtn: boolean; + disableVideo: boolean; + }; + specialTitle: string; +}; diff --git a/packages/biz/es/Demo/index.d.ts b/packages/biz/es/Demo/index.d.ts new file mode 100644 index 0000000..bcc157c --- /dev/null +++ b/packages/biz/es/Demo/index.d.ts @@ -0,0 +1,3 @@ +import React from 'react'; +declare const _default: () => React.JSX.Element; +export default _default; diff --git a/packages/biz/es/adapter/BigImageModalAdapter/index.d.ts b/packages/biz/es/adapter/BigImageModalAdapter/index.d.ts new file mode 100644 index 0000000..dab889b --- /dev/null +++ b/packages/biz/es/adapter/BigImageModalAdapter/index.d.ts @@ -0,0 +1,153 @@ +/** + * 适配老的大屏组件数据格式传入 + */ +import React from 'react'; +import { AlgorithmVersionStr, HumanProperty, ObjectType, Rect, ViewOption, AlignType, IScreenshotButtonProp, ODRECT } from '@zhst/types'; +export type TAB_TYPE = 'COMPATER' | 'NORMAL' | 'TRACK'; +export type MODEL_TYPE = 'VIDEO' | 'IMAGE'; +export interface ImgViewProps extends React.HTMLAttributes { + imageKey: string; + odRect: ODRECT; + attachImg?: Array<{ + label: string; + url: string; + }>; + showAttachImgLabel: boolean; + screenshotButtonAlign: AlignType; + screenshotButtonRender: (screenshotButtonProp: IScreenshotButtonProp) => React.ReactElement; + scale$?: number; + showCrop$?: boolean; + hideLeftTopBtn?: boolean; + score?: number; + viewOption?: ViewOption; +} +export interface VideoViewProps { + flvUrl: string; + maxDuration?: number; + screenshotButtonAlign?: AlignType; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => React.ReactElement; + defautlNormalizationRect?: Rect; + onCropChange?: (showCrop: boolean, normalizationRect: null | Rect) => void; + showCrop$?: boolean; +} +export interface CarouselProps { + hasPre?: boolean; + hasNext?: boolean; + selectIndex: number; + setSelectIndex: React.Dispatch>; + dataSource: Array<{ + key: string; + url: string; + }>; +} +export type ISelectItem = Partial> & Partial>; +export interface HeaderProps { + value: TAB_TYPE; + onChange: (type: TAB_TYPE) => void; + tabsFilter: TAB_TYPE[]; +} +export interface ImgViewRef { + imgInsRef: React.MutableRefObject; + setShowCrop: React.Dispatch>; +} +export interface VideoViewRef { + cropAble: boolean; + setShowCrop: React.Dispatch>; + downloadVideoframe: () => void; +} +export interface ParamProps { + tab: string; + selectItem: ISelectItem; + imgViewRef: React.MutableRefObject; + VideoViewRef: React.MutableRefObject; + model: MODEL_TYPE; + setModel: React.Dispatch>; + scale$: number; + showCrop$: boolean; +} +export interface BigImageData { + extendRectList: (Rect & { + algorithmVersion: AlgorithmVersionStr; + imageKey: string; + })[]; + rectList: (Rect & { + algorithmVersion: AlgorithmVersionStr; + imageKey: string; + })[]; + attachImg: { + url: string; + label: '形体' | '人脸'; + }[]; + odRect: Rect; + imageKey: string; + imgSummary: string; + objectExtImageKey: string; + attributeList: { + label: string; + list: any[]; + }[]; + archiveImages?: any; + spaceName: string; + objectType: ObjectType; + objectId: string; + bodyObjectId?: string; + faceObjectId?: string; + sourceObjectId?: string; + cameraId: string; + cameraName: string; + selectIndex: number; + humanProperty: HumanProperty; + qualityScore?: number; + score: number; + timestamp: string; + bodyImageUrl: string; + faceImageUrl: string; + algorithmVersion: AlgorithmVersionStr; + bodySpaceName: string; + faceSpaceName: string; + solutionId?: string; + [index: string]: any; +} +interface IOldImageData { + visible?: boolean; + defaultModel?: MODEL_TYPE; + onClose?: () => void; + isLoading?: boolean; + hasPre?: boolean; + hasNext?: boolean; + selectIndex?: number; + onSelectIndexChange?: (i: number) => void; + dataSource: any[]; + dataSources: any[]; + relatedData?: any[]; + transformPropFunc: (item: any) => ISelectItem; + transformVideoPropFunc: (item: ISelectItem) => Promise>; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => React.ReactElement; + showTool?: boolean; + showCarousel?: boolean; + imgViewProp?: Partial; + videoViewProp?: Partial; + ToolProps?: Partial; + nullDialogProp?: { + emptyText?: string; + }; + showHeader?: boolean; + tabsFilter?: TAB_TYPE[]; + useVirtual?: boolean; + loadNext?: (i: number) => Promise; + loadPre?: (i: number) => Promise; + children: React.ReactNode; + title?: string; + specialTitle?: string; + isRelated?: boolean; + carouselProp?: Partial; +} +export interface ToolProps { + renderRight?: (props: ParamProps) => React.ReactNode; + renderLeft?: (props: ParamProps) => React.ReactNode; + renderVideoBtn?: boolean; + param: ParamProps; + disableVideo: boolean; +} +declare const _default: (data: IOldImageData) => IOldImageData; +export default _default; diff --git a/packages/biz/es/adapter/BigImageModalAdapter/interface.d.ts b/packages/biz/es/adapter/BigImageModalAdapter/interface.d.ts deleted file mode 100644 index 6ba15d7..0000000 --- a/packages/biz/es/adapter/BigImageModalAdapter/interface.d.ts +++ /dev/null @@ -1,217 +0,0 @@ -export type CamerasStatusList = [string[], string[], string[]]; - -export type Rect = { x: number; y: number; w: number; h: number }; - -export type StatusList = { - taskOverview: any; - taskIndex: { - deviceId: string; - solutionId: string; - }; -}[]; - -export enum OperationType { - OPERATION_TYPE_UNKNOW, // 未知状态,传该值会报错 - OPERATION_TYPE_START, - OPERATION_TYPE_STOP -} - - -export enum AlgorithmVersion { - VERSION_MGN_BNN, // MGN+BNN算法 - VERSION_BNN_PRO, // BNNPRO算法 - VERSION_BNN_PRO_ATTR, // BNNPROATTR算法 - VERSION_BNN_PRO_ATTR_SCORE, // BNNPROATTR算法 - VERSION_FACE, // 人脸算法 - VERSION_HEAD, // 头肩算法 - VERSION_NON_MOTOR_VEHICLE, // 非机动车的算法 - VERSION_REID_HEAD_ATTR, // 形体头肩属性三种特征融合的算法 - VERSION_MOTOR_VEHICLE, // 机动车的算法 -} - -export enum AlgorithmVersionStr { - VERSION_MGN_BNN = 'VERSION_MGN_BNN', // MGN+BNN算法 - VERSION_BNN_PRO = 'VERSION_BNN_PRO', // BNNPRO算法 - VERSION_BNN_PRO_ATTR = 'VERSION_BNN_PRO_ATTR', // BNNPROATTR算法 - VERSION_BNN_PRO_ATTR_SCORE = 'VERSION_BNN_PRO_ATTR_SCORE', // BNNPROATTR算法 - VERSION_FACE = 'VERSION_FACE', // 人脸算法 - VERSION_HEAD = 'VERSION_HEAD', // 头肩算法 - VERSION_NON_MOTOR_VEHICLE = 'VERSION_NON_MOTOR_VEHICLE', // 非机动车的算法 - VERSION_REID_HEAD_ATTR = 'VERSION_REID_HEAD_ATTR', // 形体头肩属性三种特征融合的算法 - VERSION_MOTOR_VEHICLE = 'VERSION_MOTOR_VEHICLE', // 机动车的算法 -} - -类型枚举 -export enum ObjectType { - OBJECT_TYPE_NULL, - OBJECT_TYPE_PEDESTRAIN, - OBJECT_TYPE_BICYCLE, - OBJECT_TYPE_CAR, - OBJECT_TYPE_MOTORBIKE, - OBJECT_TYPE_AEROPLANE, - OBJECT_TYPE_BUS, - OBJECT_TYPE_TRAIN, - OBJECT_TYPE_TRUCK, - OBJECT_TYPE_MOTOR_RIDER, - OBJECT_TYPE_BIKE_RIDER, - OBJECT_TYPE_MAX, - OBJECT_TYPE_FACE = 101, -} - -// 性别 -export enum Gender { - GENDER_NONE = 'GENDER_NONE', - GENDER_MAN = 'GENDER_MAN', - GENDER_WOMAN = 'GENDER_WOMAN', -} - -// 年龄 -export enum Age { - AGE_ALL = 'AGE_ALL', - AGE_ZERO = 'AGE_ZERO', - AGE_OVERENGHTEEN = 'AGE_OVERENGHTEEN', - AGE_OVERSIXTY = 'AGE_OVERSIXTY', -} - -// 戴帽子状态 -export enum Hat { - HAT_ALL = 'HAT_ALL', - HAT_NONE = 'HAT_NONE', - HAT_OWNED = 'HAT_OWNED', -} - -// 颜色 -export enum Color { - COLOR_ALL = 'COLOR_ALL', - COLOR_BLACK = 'COLOR_BLACK', - COLOR_WHITE = 'COLOR_WHITE', - COLOR_GRAY = 'COLOR_GRAY', - COLOR_BROWN = 'COLOR_BROWN', - COLOR_PINK = 'COLOR_PINK', - COLOR_REDANDORANGE = 'COLOR_REDANDORANGE', - COLOR_YELLOW = 'COLOR_YELLOW', - COLOR_GREEN = 'COLOR_GREEN', - COLOR_BLUE = 'COLOR_BLUE', - COLOR_PURPLE = 'COLOR_PURPLE', -} - -// 背包 -export enum Package { - PACKAGE_ALL = 'PACKAGE_ALL', - PACKAGE_HANDBAG = 'PACKAGE_HANDBAG', - PACKAGE_BACKPACK = 'PACKAGE_BACKPACK', - PACKAGE_SHOULDERBAG = 'PACKAGE_SHOULDERBAG', - PACKAGE_OTHER = 'PACKAGE_OTHER', - PACKAGE_NONE = 'PACKAGE_NONE', -} - -// 行走模式 -export enum WalkPattern { - WALKPATTERN_ALL = 'WALKPATTERN_ALL', - WALKPATTERN_WALK = 'WALKPATTERN_WALK', - WALKPATTERN_RIDING = 'WALKPATTERN_RIDING', -} - -// 人类属性 -export interface HumanProperty { - age: Age; - downColor: Color; - gender: Gender; - hat: Hat; - package: Package; - upColor: Color; - walkPattern: WalkPattern; -} - -// 人类属性枚举 -export interface EnumHumanProperty { - Gender: typeof Gender; - Age: typeof Age; - Hat: typeof Hat; - Color: typeof Color; - Package: typeof Package; - WalkPattern: typeof WalkPattern; -} - -export interface IScreenshotButtonProp { - model: 'VIDEO' | 'IMAGE'; - getCropInfo: () => Promise; - setShowCrop: React.Dispatch>; - cropType: typeof cropType[number]; - selectAlgorithmVersion: number; -} - -export interface AlignType { - /** - * move point of source node to align with point of target node. - * Such as ['tr','cc'], align top right point of source node with center point of target node. - * Point can be 't'(top), 'b'(bottom), 'c'(center), 'l'(left), 'r'(right) */ - points?: AlignPoint[]; - /** - * offset source node by offset[0] in x and offset[1] in y. - * If offset contains percentage string value, it is relative to sourceNode region. - */ - offset?: number[]; - /** - * offset target node by offset[0] in x and offset[1] in y. - * If targetOffset contains percentage string value, it is relative to targetNode region. - */ - targetOffset?: number[]; - /** - * If adjustX field is true, will adjust source node in x direction if source node is invisible. - * If adjustY field is true, will adjust source node in y direction if source node is invisible. - */ - overflow?: { - adjustX?: boolean | number; - adjustY?: boolean | number; - }; - /** - * Whether use css right instead of left to position - */ - useCssRight?: boolean; - /** - * Whether use css bottom instead of top to position - */ - useCssBottom?: boolean; - /** - * Whether use css transform instead of left/top/right/bottom to position if browser supports. - * Defaults to false. - */ - useCssTransform?: boolean; - ignoreShake?: boolean; -} - -export type ODRECT = { - topleft: { - x: number; - y: number; - }; - width: number; - height: number; -}; - -export interface ViewOption { - /* 图片url */ - image?: string | HTMLImageElement; - - /* 缩放灵敏度(0,1],default: 0.1 */ - wheelZoomRatio?: number; - - /* - * 是否允许缩放 - * @default: true - */ - scaleAble?: boolean; - - /* - * 是否允许拖拽 - * @default: true - */ - dragAble?: boolean; - - /* - * fit scale 作为 最小缩放 - * @default: false - */ - fitScaleAsMinScale?: boolean; -} diff --git a/packages/biz/es/adapter/index.d.ts b/packages/biz/es/adapter/index.d.ts new file mode 100644 index 0000000..f1dd564 --- /dev/null +++ b/packages/biz/es/adapter/index.d.ts @@ -0,0 +1 @@ +export { default as BigImageModalAdapter } from './BigImageModalAdapter'; diff --git a/packages/biz/es/hooks/useIntelligentTracking/index.d.ts b/packages/biz/es/hooks/useIntelligentTracking/index.d.ts new file mode 100644 index 0000000..c1e54ef --- /dev/null +++ b/packages/biz/es/hooks/useIntelligentTracking/index.d.ts @@ -0,0 +1,45 @@ +import { Dayjs as Moment } from 'dayjs'; +export declare const getDefaultRadius: () => number; +export declare const setDefaultRadius: (radius: number) => void; +export declare const setSearchIntervalDuration: (duration: number) => void; +export declare const getSearchIntervalDuration: (time: number) => number; +export declare const operateTrackById: (smartTrackId: number, operationType: OperationType) => Promise; +export declare const deleteTrackById: (smartTrackId: number) => Promise; +export declare const modifyTrackImgs: (smartTrackId: number, images: Array) => Promise; +export declare const modifyTrackConf: (conf: any, smartTrackId: number) => Promise; +export declare const getTrackTaskById: (smartTrackId?: number) => Promise; +export declare const getTackDetailInfo: (smartTrackId?: number) => Promise; +export declare const getTaskCameraByCenterAndPower: (value: { + taskPower: { + facePower: number; + bodyPower: number; + }; + cameraInfos: Array; + center: [number, number]; +}) => Promise; +/**创建追踪任务 */ +export declare const createIntelligentTrack: (value: { + images: Array; + deviceIds: Array; + circleCenter: [number, number]; + model: number; + circleRadius: number; + facePower?: number; + bodyPower?: number; + historyTime?: [Moment, Moment]; + topping?: boolean; +}) => Promise; +export declare const emitHeartbeat: (smartTrackId: number) => Promise; +export declare const ModifyTrackCameras: (value: { + smartTrackId: number; + deviceIds: Array; + centerPoint: [number, number]; +}) => Promise; +export declare const setIntelligentTrackCircleInfo: (smartTrackId: number, circleCenter: [number, number]) => Promise; +export declare const getTackCameraInfo: (value: { + circleCenter: [Moment, Moment]; + radius: number; + zoom: number; +}) => Promise; +export declare const getCameraInfoByCircle: (circleCenter: any, radius: any, zoom?: number) => Promise; +export declare const taskInfoToSearchItem: (taskInfo: any) => any[]; diff --git a/packages/biz/es/index.d.ts b/packages/biz/es/index.d.ts new file mode 100644 index 0000000..ac47c74 --- /dev/null +++ b/packages/biz/es/index.d.ts @@ -0,0 +1,3 @@ +export { default as Demo } from './Demo'; +export * from './adapter'; +export { default as BigImageModal } from './BigImageModal'; diff --git a/packages/biz/es/useSocket/index.d.ts b/packages/biz/es/useSocket/index.d.ts new file mode 100644 index 0000000..08018b5 --- /dev/null +++ b/packages/biz/es/useSocket/index.d.ts @@ -0,0 +1,26 @@ +export declare const SocketApi: { + CameraTaskStatue: string; + DeviceStatus: string; + SubscribeSolutionDeploy: string; + SubscribeTasksSummary: string; + MonitorSubscribeResult: string; + MonitorSubscribeStatus: string; + SubscribeArchiveGroupUpload: string; + SubscribeJointTask: string; + SubscribeGroupFragment: string; + SubscribeGroup: string; + SubscribeStreamEvent: string; +}; +type ApiKeys = keyof typeof SocketApi; +declare const _default: (topic: ApiKeys, iterator?: any, opt?: { + req?: { + [key: string]: any; + } | undefined; + throttle?: number | undefined; + parseData?: boolean | undefined; + beforeLoopTmp?: Function | undefined; + shouldBreak: boolean; + forceRefresh: any; + close?: boolean | undefined; +} | undefined) => void; +export default _default; diff --git a/packages/biz/es/useSocket/onceChannel.d.ts b/packages/biz/es/useSocket/onceChannel.d.ts new file mode 100644 index 0000000..400ffa7 --- /dev/null +++ b/packages/biz/es/useSocket/onceChannel.d.ts @@ -0,0 +1,2 @@ +declare const startChannel: (topic: any, req: any, callback: any) => () => void; +export default startChannel; diff --git a/packages/biz/es/useSocket/ws.d.ts b/packages/biz/es/useSocket/ws.d.ts new file mode 100644 index 0000000..cb4f172 --- /dev/null +++ b/packages/biz/es/useSocket/ws.d.ts @@ -0,0 +1,31 @@ +/// +/// +/// +/// +/// +declare class Channel { + /** + * io 实例化对象 + */ + ioIns: any; + /** + * 已存在的订阅列表 + */ + listeners: never[]; + /** + * 调试信息 记录订阅/反订阅次数 + */ + subscribeListenerId: never[]; + unSubscribeListenerId: never[]; + init: () => void; + retry: (listener: { + [x: string]: any; + lastRetryInterval: number | undefined; + intervalId: NodeJS.Timeout; + } | undefined) => void; + doEmit: (topic: any, req: any, listenerId: any) => void; + subscribe(topic: any, req: any, handle: any): () => void; + unSubscribe(topic: any, req: any, handleId: any, listenerId: any): void; +} +declare const channelIns: Channel; +export default channelIns; diff --git a/packages/biz/es/useSocket/ws.js b/packages/biz/es/useSocket/ws.js index 9e15735..8e53d9c 100644 --- a/packages/biz/es/useSocket/ws.js +++ b/packages/biz/es/useSocket/ws.js @@ -5,6 +5,7 @@ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _d function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +// @ts-nocheck import { v4 as uuidv4 } from 'uuid'; import { has } from '@zhst/func'; import io from 'socket.io-client'; diff --git a/packages/biz/es/utils/constants.d.ts b/packages/biz/es/utils/constants.d.ts new file mode 100644 index 0000000..45a9a99 --- /dev/null +++ b/packages/biz/es/utils/constants.d.ts @@ -0,0 +1,23 @@ +export declare const OBJECT_GRNER_THRESHOLD = 0.8; +export declare const OBJECT_AGE_TYPE_THRESHOLD = 0.5; +export declare const MODE_KEY = "test_mode"; +export declare const SEARCH_IMG_COUNT = 10; +export declare const GLOBAL_IS_ITEM_NUMBER_SHOW = false; +export declare const publicPath = "hummingbird"; +export declare const ENTER_CIRCLE = "MONITORTYPE_ENTER_CIRCLE"; +export declare const OUT_CIRCLE = "MONITORTYPE_OUT_CIRCLE"; +export declare const TEMP = "MONITORTYPE_TEMP"; +export declare const GLOBAL_IS_BOX_VMS_SHOW = true; +export declare const BODY_SEARCH_THRESHOID = 0.45; +export declare const RECORD_VERSION = "3.0.0"; +export declare const DeviceTab: { + EMPTY: number; + REAL_CAMERA: number; + PREPROCESS_CAMERA: number; + TAG_CAMERA: number; + HISTORY_VIDEO_GROUP: number; + VIRTUAL_CAMERA: number; + REAL_CAMERA_NOFACE: number; + REAL_CAMERA_ONLYFACE: number; + REAL_CAMERA_NOFACE_NOBOX_NODIRECONNECT: number; +}; diff --git a/packages/biz/es/utils/constants.js b/packages/biz/es/utils/constants.js index 7cb4646..1ad86ba 100644 --- a/packages/biz/es/utils/constants.js +++ b/packages/biz/es/utils/constants.js @@ -1,16 +1,6 @@ -export var isDev = import.meta.env.DEV; -export var host = isDev ? 'http://10.0.0.7' : "".concat(location.protocol, "//").concat(location.hostname); -export var port = isDev ? '30003' : location.port; -export var ProjectUrl = "".concat(host, ":").concat(port); -export var MANAGER_URL = port ? ProjectUrl + '/manager' : host + '/manager'; -export var S3_HOST = location.port ? "".concat(host, ":").concat(port) : host; -export var MapUrl = port ? ProjectUrl + '/map' : host + '/map'; -export var S3_V3_HOST = host; //minio 地址 -export var SOCKET_HOST = port ? ProjectUrl : host; export var OBJECT_GRNER_THRESHOLD = 0.8; //目标图判断性别阈值 export var OBJECT_AGE_TYPE_THRESHOLD = 0.5; //目标图判断年龄段阈值 export var MODE_KEY = 'test_mode'; -export var ROUTER_SHOULD_FILTER = isDev; //是否根据后台配置路由,开发环境全打开 //业务约定 export var SEARCH_IMG_COUNT = 10; //检索图片的最大个数 export var GLOBAL_IS_ITEM_NUMBER_SHOW = false; //是否展示索引 diff --git a/packages/biz/es/global.d.ts b/packages/biz/es/utils/index.d.ts similarity index 100% rename from packages/biz/es/global.d.ts rename to packages/biz/es/utils/index.d.ts diff --git a/packages/biz/lib/BigImageModal/BigImageModal.d.ts b/packages/biz/lib/BigImageModal/BigImageModal.d.ts new file mode 100644 index 0000000..05eab4a --- /dev/null +++ b/packages/biz/lib/BigImageModal/BigImageModal.d.ts @@ -0,0 +1,23 @@ +import React from 'react'; +import type { ModalProps, DescriptionsProps, TabsProps } from 'antd'; +import './index.less'; +export declare const componentPrefix = "zhst-image"; +export interface BigImageModalProps extends ModalProps { + visible: boolean; + descriptionConfig: { + data: { + title: string; + children: Pick; + }[]; + }; + tabsConfig: { + data: Pick & { + key: 'NORMAL' | 'COMPATER' | 'TRACK'; + }; + }; + dataSource: any; + imageData: any; + relatedData: any; +} +declare const BigImageModal: React.FC; +export default BigImageModal; diff --git a/packages/biz/lib/BigImageModal/BigImageModal.js b/packages/biz/lib/BigImageModal/BigImageModal.js new file mode 100644 index 0000000..7973124 --- /dev/null +++ b/packages/biz/lib/BigImageModal/BigImageModal.js @@ -0,0 +1,169 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImageModal/BigImageModal.tsx +var BigImageModal_exports = {}; +__export(BigImageModal_exports, { + componentPrefix: () => componentPrefix, + default: () => BigImageModal_default +}); +module.exports = __toCommonJS(BigImageModal_exports); +var import_react = __toESM(require("react")); +var import_antd = require("antd"); +var import_classnames = __toESM(require("classnames")); +var import_func = require("@zhst/func"); +var import_index = require("./index.less"); +var import_navigation = __toESM(require("./components/navigation")); +var DescriptionsItem = import_antd.Descriptions.Item; +var componentPrefix = "zhst-image"; +var initialStyle = { + fontSize: "12px" +}; +var BigImageModal = (props) => { + const { + title = "-", + open, + visible, + children, + descriptionConfig = { + data: [] + }, + tabsConfig = { + data: [ + { + label: "对比图模式", + key: "1", + children: "对比图组件" + }, + { + label: "场景图模式", + key: "2", + children: "场景图组件" + } + ] + }, + dataSource = [], + imageData = [], + relatedData = [] + } = props; + const showCropRef = (0, import_react.useRef)(false); + const scaleRef = (0, import_react.useRef)(0); + const [activeKey, setActiveKey] = (0, import_react.useState)((0, import_func.get)(tabsConfig, "data[0].key")); + const [previewIndex, setPreviewIndex] = (0, import_react.useState)(0); + const [isRelated, setIsRelated] = (0, import_react.useState)(false); + return /* @__PURE__ */ import_react.default.createElement( + import_antd.Modal, + { + destroyOnClose: true, + open: open || visible, + footer: null, + className: componentPrefix, + title, + ...props + }, + descriptionConfig.data.map((descriptions) => { + var _a; + return /* @__PURE__ */ import_react.default.createElement( + import_antd.Descriptions, + { + key: descriptions.title, + title: /* @__PURE__ */ import_react.default.createElement("p", { style: { margin: "12px 0 0", fontSize: initialStyle.fontSize } }, descriptions.title), + column: 8, + style: { padding: "0 64px" } + }, + (_a = descriptions == null ? void 0 : descriptions.children) == null ? void 0 : _a.map((item) => /* @__PURE__ */ import_react.default.createElement( + DescriptionsItem, + { + key: item.key, + label: item.label, + span: 1, + contentStyle: { fontSize: initialStyle.fontSize }, + labelStyle: { fontSize: initialStyle.fontSize } + }, + item.children + )) + ); + }), + /* @__PURE__ */ import_react.default.createElement( + import_antd.Tabs, + { + defaultActiveKey: activeKey, + centered: true, + tabBarStyle: { fontSize: "18px" }, + items: tabsConfig.data, + ...tabsConfig + } + ), + /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)(`${componentPrefix}-view-container`), + style: activeKey === "TRACK" ? { + height: "718px", + marginBottom: "0px" + } : {} + }, + activeKey !== "TRACK" && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( + import_navigation.default, + { + className: (0, import_classnames.default)( + `${componentPrefix}-view-container__nav`, + previewIndex <= 0 && `${componentPrefix}-view-container__nav--disabled`, + `${componentPrefix}-view-container__nav--left` + ), + show: isRelated ? imageData.length > 1 : dataSource.length > 1, + disabled: previewIndex <= 0, + prev: true, + onClick: () => { + setPreviewIndex((pre) => pre - 1); + } + } + ), /* @__PURE__ */ import_react.default.createElement( + import_navigation.default, + { + className: (0, import_classnames.default)( + `${componentPrefix}-view-container__nav`, + (previewIndex >= imageData.length - 1 || previewIndex >= dataSource.length - 1) && `${componentPrefix}-view-container__nav--disabled`, + `${componentPrefix}-view-container__nav--right` + ), + show: isRelated ? imageData.length > 1 : dataSource.length > 1, + disabled: previewIndex >= imageData.length - 1 || previewIndex >= dataSource.length - 1, + next: true, + onClick: async (e) => { + setPreviewIndex((pre) => pre + 1); + } + } + )) + ) + ); +}; +var BigImageModal_default = BigImageModal; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + componentPrefix +}); diff --git a/packages/biz/lib/BigImageModal/components/navigation/index.d.ts b/packages/biz/lib/BigImageModal/components/navigation/index.d.ts new file mode 100644 index 0000000..78b1ca8 --- /dev/null +++ b/packages/biz/lib/BigImageModal/components/navigation/index.d.ts @@ -0,0 +1,13 @@ +import * as React from 'react'; +import './index.less'; +declare const Navigation: React.FC<{ + show?: boolean; + onClick?: React.MouseEventHandler; + prev?: boolean; + next?: boolean; + disabled?: boolean; + className?: string; + color?: string; + hoverColor?: string; +}>; +export default Navigation; diff --git a/packages/biz/lib/BigImageModal/components/navigation/index.js b/packages/biz/lib/BigImageModal/components/navigation/index.js new file mode 100644 index 0000000..d7cc187 --- /dev/null +++ b/packages/biz/lib/BigImageModal/components/navigation/index.js @@ -0,0 +1,58 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImageModal/components/navigation/index.tsx +var navigation_exports = {}; +__export(navigation_exports, { + default: () => navigation_default +}); +module.exports = __toCommonJS(navigation_exports); +var React = __toESM(require("react")); +var import_classnames = __toESM(require("classnames")); +var import_antd = require("antd"); +var import_meta = require("@zhst/meta"); +var import_index = require("./index.less"); +var componentName = `zhst-image__nav`; +var Navigation = (props) => { + const { show, prev, next, disabled, onClick, className, color } = props; + return /* @__PURE__ */ React.createElement( + "div", + { + className: (0, import_classnames.default)( + `${componentName}`, + prev && `${componentName}-prev`, + next && `${componentName}-next`, + disabled && `${componentName}--disable`, + !show && `${componentName}--hide`, + className + ) + }, + /* @__PURE__ */ React.createElement(import_antd.Button, { type: "text", disabled, onClick }, /* @__PURE__ */ React.createElement(import_meta.Icon, { size: 28, color, icon: prev ? "icon-qiehuanzuo" : "icon-qiehuanyou" })) + ); +}; +var navigation_default = Navigation; diff --git a/packages/biz/lib/BigImageModal/components/navigation/index.less b/packages/biz/lib/BigImageModal/components/navigation/index.less new file mode 100644 index 0000000..0a834f9 --- /dev/null +++ b/packages/biz/lib/BigImageModal/components/navigation/index.less @@ -0,0 +1,44 @@ +.zhst-image__nav { + position: absolute; + display: flex; + width: 48px; + height: 100%; + flex-shrink: 0; + align-items: center; + justify-content: center; + cursor: pointer; + font-size: 0; + + &>button { + & span { + display: flex; + } + } + + :global { + i:hover { + color: #f0f0f0 !important; + } + } + + &--disable { + :global { + i { + color: #f0f0f0; + cursor: not-allowed !important; + } + } + } + + &--hide { + display: none; + } + + &-prev { + left: 20px; + } + + &-next { + right: 20px; + } +} diff --git a/packages/meta/es/ImagePreview/images/emptyImage.png b/packages/biz/lib/BigImageModal/images/emptyImage.png similarity index 100% rename from packages/meta/es/ImagePreview/images/emptyImage.png rename to packages/biz/lib/BigImageModal/images/emptyImage.png diff --git a/packages/meta/es/ImagePreview/images/percent_background.png b/packages/biz/lib/BigImageModal/images/percent_background.png similarity index 100% rename from packages/meta/es/ImagePreview/images/percent_background.png rename to packages/biz/lib/BigImageModal/images/percent_background.png diff --git a/packages/biz/lib/BigImageModal/index.d.ts b/packages/biz/lib/BigImageModal/index.d.ts new file mode 100644 index 0000000..bb07714 --- /dev/null +++ b/packages/biz/lib/BigImageModal/index.d.ts @@ -0,0 +1,3 @@ +import BigImageModal from "./BigImageModal"; +export type { BigImageModalProps } from './BigImageModal'; +export default BigImageModal; diff --git a/packages/biz/lib/BigImageModal/index.js b/packages/biz/lib/BigImageModal/index.js new file mode 100644 index 0000000..93ee703 --- /dev/null +++ b/packages/biz/lib/BigImageModal/index.js @@ -0,0 +1,36 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImageModal/index.tsx +var BigImageModal_exports = {}; +__export(BigImageModal_exports, { + default: () => BigImageModal_default +}); +module.exports = __toCommonJS(BigImageModal_exports); +var import_BigImageModal = __toESM(require("./BigImageModal")); +var BigImageModal_default = import_BigImageModal.default; diff --git a/packages/biz/lib/BigImageModal/index.less b/packages/biz/lib/BigImageModal/index.less new file mode 100644 index 0000000..966b5d6 --- /dev/null +++ b/packages/biz/lib/BigImageModal/index.less @@ -0,0 +1,770 @@ +.zhst-image { + .zhst-dialog-content { + box-shadow: 0 4px 12px rgb(0 0 0 / 20%); + } + + + &-view-container { + position: relative; + width: 100%; + height: 532px; + margin-bottom: 16px; + + &__nav { + position: absolute; + z-index: 99; + top: 50%; + width: 40px !important; + height: 40px !important; + background: #d9d9d9; + border-radius: 100%; + cursor: pointer; + transform: translateY(-50%); + + &>button { + display: flex; + align-items: center; + color: #fff !important; + } + + &--disabled { + opacity: 0.3; + + &>button { + color: #fff !important; + } + } + } + + &__nav:hover { + background: #09f; + color: #fff !important; + } + } + + &-tool-container { + width: 100%; + height: 40px; + margin-bottom: 16px; + } + + &__face-score { + position: absolute; + right: 90px; + bottom: 80px; + color: red; + font-family: 'Microsoft YaHei'; + font-size: 19px; + font-weight: bold; + } + + &-carousel-container { + position: relative; + width: 100%; + height: 100px; + margin-top: 16px; + margin-bottom: 24px; + } +} + + +.zhst-image__tool { + display: flex; + width: 100%; + align-items: center; + font-size: 14px; + + &-split { + width: 0; + height: 14px; + + &::before { + display: block; + height: 100%; + border-left: 1px solid #e6e7eb; + content: ''; + } + } + + &-zoom { + display: inline-flex; + align-items: center; + + &> :not(:last-child) { + margin-right: 14px; + } + + &__scale { + display: inline-block; + width: 38px; + height: 14px; + + // margin-left: 15px; + box-sizing: content-box; + border: 1px solid rgb(77 77 77 / 100%); + margin-top: 2px; //对齐 + background: rgb(255 255 255 / 100%); + border-radius: 2px; + color: #4d4d4d; + cursor: default; + font-size: 12px; + line-height: 14px; + text-align: center; + } + } + + &-switch { + display: flex; + width: 30px; + flex-shrink: 0; + align-items: center; + justify-content: center; + margin: 0 26px; + } + + &-left { + display: flex; + flex: 1; + align-items: center; + justify-content: flex-end; + + &> :not(:last-child) { + margin-right: 14px; + } + } + + &-right { + display: flex; + flex: 1; + align-items: center; + justify-content: flex-start; + + &> :not(:first-child) { + margin-left: 20px; + } + } + + &-icon-container { + font-size: 14px; + + &--active { + color: #5584ff !important; + } + + &> :first-child { + margin-right: 2px; + } + } +} + +.zhst-image__carousel { + position: relative; + display: flex; + width: 742px; + height: 100px; + align-items: center; + justify-content: center; + border: 1px solid #f0f0f0; + margin: 0 auto; + background: #fafafa; + border-radius: 2px; + user-select: none; + + &-container { + width: (58px + 8px) * 10; + } + + &-item { + display: flex; + width: 58px + 8px; + align-items: center; + justify-content: center; + } + + &-item-img { + /* 尝试消除transform 副作用 */ + position: relative; + z-index: 99; + + // width: 58px; + // height: 76px; + display: flex; + width: 66px; + height: 84px; + box-sizing: border-box; + align-items: center; + justify-content: center; + background: #fafafa; + cursor: pointer; + + /* 尝试消除transform 副作用 end */ + &--active { + border: 2px solid #09f; + border-radius: 1px; + } + + &>div { + /* 尝试消除transform 副作用 */ + position: relative; + z-index: 99; + overflow: hidden; + width: 58px; + height: 76px; + + /* 尝试消除transform 副作用 end */ + &>img { + width: 58px; + height: 76px; + object-fit: contain; + transition: all 0.2s; + + &:hover { + transform: scale(1.5); + } + } + } + } +} + +.zhst-image__header { + width: 100%; + // margin-top: 3px; + margin-bottom: 10px; + + &__pad0 { + padding: 0; + } + + &__pad66 { + padding: 0 66px; + } + + &__bar { + display: flex; + width: 100%; + background: #f6f6f6; + // box-shadow: 0px 0px 8px 0px rgba(172, 172, 172, 0.5); + justify-content: center; + // border-color: #f0f0f0; + // border-bottom-width: 1px; + // border-bottom-style: solid; + } + + &__barNoColor { + display: flex; + width: 100%; + justify-content: center; + border-color: #f0f0f0; + border-bottom-width: 1px; + border-bottom-style: solid; + } + + &__item { + position: relative; + display: flex; + height: 40px; + align-items: center; + justify-content: center; + margin: 0 15px; + color: #999; + cursor: pointer; + font-size: 14px; + font-weight: bold; + line-height: 19px; + transition: font-size 0.3s ease; + + &:hover { + // font-size: 18px; + color: #333; + } + + &::before { + position: absolute; + bottom: 0; + left: 50%; + width: 0; + border-bottom: 2px solid #09f; + content: ''; + transition: all 0.3s ease; + } + + &--active { + background-color: transparent; + color: #333; + font-size: 18px; + + // color: #0099ff; + &::before { + left: 0; + width: 100%; + } + } + } +} + + +.zhst-image__compater-view { + display: flex; + width: 100%; + align-items: center; + justify-content: center; + + &>div:first-child { + margin-right: 25px; + } + + &>div:last-child { + margin-left: 25px; + } + + &__container { + position: relative; + width: 345px; + height: 460px; + box-sizing: content-box; + border: 1px solid #f0f0f0; + } + + &__view { + width: 345px; + height: 460px; + } + + &__label { + position: absolute; + z-index: 99; + top: 0; + left: 0; + display: flex; + height: 34px; + align-items: center; + justify-content: center; + + // width: 48px; + padding: 0 6px; + background: #09f; + color: #fff; + } + + &__tool { + display: flex; + width: 345px; + height: 40px; + align-items: center; + justify-content: center; + background: #f9f9f9; + + i, + span { + color: #333 !important; + } + + i { + margin-right: 4px; + } + + &>*:not(:last-child) { + margin-right: 20px; + } + + &__scale { + display: inline-block; + width: 38px; + height: 16px; + + // margin-left: 15px; + box-sizing: content-box; + border: 1px solid rgb(77 77 77 / 100%); + background: rgb(255 255 255 / 100%); + border-radius: 2px; + color: #4d4d4d; + cursor: default; + font-size: 12px; + line-height: 16px; + text-align: center; + } + + &__line { + width: 1px; + height: 14px; + background: #e6e6e6; + } + } + + &__empty { + position: absolute; + z-index: 9; + display: flex; + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background: #f9f9f9; + transform: translateY(-100%); + + &>img { + width: 140px; + height: 80px; + } + + &--text { + color: #999; + font-size: 14px; + line-height: 22px; + } + } + + &__scoll-module { + position: absolute; + top: 0%; + left: 0%; + display: flex; + width: 100%; + height: 100%; + align-items: flex-end; + justify-content: space-between; + pointer-events: none; + + &__btn { + display: flex; + width: 50px; + height: 50px; + align-items: center; + justify-content: center; + margin: 6px; + border-radius: 50%; + opacity: 0.5; + pointer-events: all; + + &>span { + display: flex; + align-items: center; + justify-content: center; + } + } + + &__btn:hover { + background-color: #09f !important; + color: #fff !important; + } + } +} + +.zhst-image__trackmodel { + &__panel { + position: relative; + z-index: 99; + top: 0; + right: 0; + width: 320px; + height: 100%; + background-color: #fff; + + &--head { + width: 100%; + height: 40px; + padding: 0 16px; + border-bottom: 1px solid #f0f0f0; + color: #333; + font-size: 14px; + font-weight: bold; + line-height: 40px; + text-align: left; + } + + &--track { + height: calc(100% - 40px); + } + + &-date { + padding: 10px 6px; + + // position: absolute; + } + } + + &--bigImage { + position: absolute; + z-index: 100; + top: 0; + left: 0; + display: flex; + width: 100%; + height: 100%; + justify-content: center; + padding-top: 59px; + background: rgb(0 0 0 / 40%); + + &--image { + width: 946px; + height: 532px; + + &>img { + width: 946px; + height: 532px; + object-fit: contain; + } + } + + &--close { + margin-left: 16px; + color: #fff; + } + } + + &__flooter { + position: absolute; + z-index: 999; + bottom: -124px; + left: 0; + width: calc(100% - 320px - 10px); + height: 144px; + background: #fff; + box-shadow: 0 0 8px 0 rgb(172 172 172 / 50%); + + &--head { + display: flex; + height: 20px; + align-items: center; + justify-content: center; + background: #f6f6f6; + color: #999; + line-height: 16px; + } + + &--body { + display: flex; + height: calc(100% - 20px); + padding-left: 50px; + + &__title { + color: #333; + font-size: 12px; + font-weight: bold; + line-height: 16px; + } + + &__text { + overflow: hidden; + color: #333; + font-size: 12px; + line-height: 16px; + text-overflow: ellipsis; + white-space: nowrap; + } + + &--left { + display: flex; + width: 75px; + height: 100; + align-items: center; + + &>img { + width: 75px; + height: 100px; + object-fit: contain; + } + } + + &--middle { + display: grid; + width: 331px; + justify-content: flex-start; + padding: 8px 20px; + border-right: 1px solid #f0f0f0; + + &>div { + display: flex; + } + } + + &--right { + display: grid; + width: calc(100% - 331px - 75px); + padding: 8px 20px; + + &>div { + display: flex; + } + + &__button-list { + display: flex; + align-items: center; + + &>button { + margin-right: 20px; + + &>span { + color: #09f !important; + } + + &:hover { + &>span { + color: #247fdb !important; + } + } + } + } + } + } + + @keyframes close { + from { + bottom: 0; + } + + to { + bottom: -124px; + } + } + + @keyframes open { + from { + bottom: -124px; + } + + to { + bottom: 0; + } + } + + &--close { + bottom: -124px; + animation-duration: 1s; + animation-name: close; + } + + &--open { + bottom: 0; + animation-duration: 1s; + animation-name: open; + } + } +} + +.zhst-image__null { + display: flex; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + + &__text { + // margin-left: 105px; + margin-top: 8px; + color: #999; + font-size: 14px; + width: 100%; + text-align: center; + } +} + +.zhst-image__attributePanel { + margin: 0 66px; + background: #f6f6f6; + margin-top: 20px; + padding-top: 16px; + display: flex; + justify-content: center; + + &>div:first-child { + width: fit-content; + display: flex; + flex-direction: column; + } + + &-title { + color: rgb(0 0 0 / 88%); + font-weight: bold; + padding-bottom: 12px; + } + + &-item { + display: flex; + } + + &-label { + color: rgb(0 0 0 / 45%); + } + + &-value { + color: rgb(0 0 0 / 88%); + } +} + +.relatedWrapper { + width: 100%; + height: 100px; + padding: 0 30px; + margin-bottom: 30px; + box-sizing: border-box; + + .relatedTabs { + width: 100%; + height: 100px; + } + + .relatedContent { + width: 100%; + height: 100px; + display: flex; + + .relatedPics { + width: 742px; + height: 100px; + // display: flex; + // box-sizing: border-box; + // background: #fafafa; + // border-radius: 2px; + // border: 1px solid #f0f0f0; + // .LeftBtn, + // .RighttBtn { + // width: 34px; + // height: 100%; + // display: flex; + // justify-content: center; + // align-items: center; + // } + // .ListContent { + // flex: 1; + // height: 100%; + // } + } + + .disabled { + color: rgba(0, 0, 0, 25%); + } + + .relatedBtn { + flex: 1; + font-size: 14px; + color: #333; + display: flex; + align-items: flex-end; + cursor: pointer; + + &:hover { + color: #09f; + } + } + } + + :global { + .ant-tabs-left>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane { + padding-left: 16px; + } + + .ant-tabs-tab { + padding: 8px 12px !important; + text-align: right !important; + } + + .ant-tabs .ant-tabs-tab { + font-size: 14px; + font-weight: bold; + text-align: right; + justify-content: flex-end; + } + } +} diff --git a/packages/biz/lib/BigImageModal/mock.d.ts b/packages/biz/lib/BigImageModal/mock.d.ts new file mode 100644 index 0000000..257ed75 --- /dev/null +++ b/packages/biz/lib/BigImageModal/mock.d.ts @@ -0,0 +1,294 @@ +export declare const IMAGE_DATA: { + enAbleDeleteFeature: boolean; + tabsFilter: string[]; + dataSources: { + objectId: string; + condition: { + featureInfo: null; + featureData: string; + imageData: string; + alg: string; + rect: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageUrl: string; + srcImageUrl: string; + }; + score: number; + timestamp: number; + deviceId: string; + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + objectIndex: { + objectId: string; + solutionId: string; + deviceId: string; + fragmentId: string; + }; + objectType: string; + isObjectTrack: boolean; + pathId: string; + frameInfo: { + frameId: string; + frameTimestamp: string; + width: number; + height: number; + originWidth: number; + originHeight: number; + offsetTime: string; + skipNumber: string; + }; + level: number; + bboxInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + bboxExtInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageKey: string; + objectExtImageKey: string; + frameImageKey: string; + confidence: number; + sourceObjectId: string; + storeTimestamp: string; + gbNumber: string; + qualityScore: number; + subObjectCount: number; + subObjectType: string[]; + subObjectIds: string[]; + cameraInfo: { + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + }; + solutionId: string; + fragmentId: string; + contrastKey: string; + compaterImages: string[]; + imgSummary: string; + imageKey: string; + srcImageUrl: string; + algorithmVersion: string; + cameraId: string; + cameraName: string; + }[]; + selectIndex: number; + disableBtn: number[]; + dataSource: { + objectId: string; + condition: { + featureInfo: null; + featureData: string; + imageData: string; + alg: string; + rect: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageUrl: string; + srcImageUrl: string; + }; + score: number; + timestamp: number; + deviceId: string; + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + objectIndex: { + objectId: string; + solutionId: string; + deviceId: string; + fragmentId: string; + }; + objectType: string; + isObjectTrack: boolean; + pathId: string; + frameInfo: { + frameId: string; + frameTimestamp: string; + width: number; + height: number; + originWidth: number; + originHeight: number; + offsetTime: string; + skipNumber: string; + }; + level: number; + bboxInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + bboxExtInFrame: { + x: number; + y: number; + w: number; + h: number; + }; + objectImageKey: string; + objectExtImageKey: string; + frameImageKey: string; + confidence: number; + sourceObjectId: string; + storeTimestamp: string; + gbNumber: string; + qualityScore: number; + subObjectCount: number; + subObjectType: string[]; + subObjectIds: string[]; + cameraInfo: { + id: string; + name: string; + dirid: string; + status: string; + longitude: number; + latitude: number; + caseId: string; + caseGroup: string; + isDeleted: string; + extendInfo: { + vmsPlatformId: string; + vmsChannel: string; + vmsCameraDecoderTag: string; + platformPluginType: string; + deviceVender: string; + type: string; + ip: string; + port: string; + username: string; + passwd: string; + rtspAddress: string; + facesnapChannel: string; + edgeDeviceSn: string; + platform1400Id: number; + useRtspAddress: boolean; + frameCheck: boolean; + frameRectX: number; + frameRectY: number; + frameRectW: number; + frameRectH: number; + edgeNodeId: string; + processStatus: string; + }; + }; + solutionId: string; + fragmentId: string; + contrastKey: string; + compaterImages: string[]; + imgSummary: string; + imageKey: string; + srcImageUrl: string; + algorithmVersion: string; + cameraId: string; + cameraName: string; + }[]; + isArchiveDetail: boolean; + ToolProps: { + renderVideoBtn: boolean; + disableVideo: boolean; + }; + specialTitle: string; +}; diff --git a/packages/biz/lib/BigImageModal/mock.js b/packages/biz/lib/BigImageModal/mock.js new file mode 100644 index 0000000..e3072e9 --- /dev/null +++ b/packages/biz/lib/BigImageModal/mock.js @@ -0,0 +1,930 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImageModal/mock.ts +var mock_exports = {}; +__export(mock_exports, { + IMAGE_DATA: () => IMAGE_DATA +}); +module.exports = __toCommonJS(mock_exports); +var IMAGE_DATA = { + "enAbleDeleteFeature": true, + "tabsFilter": [ + "COMPATER", + "NORMAL" + ], + "dataSources": [ + { + "objectId": "1742110565582518272", + "condition": { + "featureInfo": null, + "featureData": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", + "imageData": "", + "alg": "VERSION_REID_HEAD_ATTR", + "rect": { + "x": 0.271875, + "y": 0.32222223, + "w": 0.2859375, + "h": 0.67777777 + }, + "objectImageUrl": "singer-20240102/1/129529/1742047651878156288.jpg", + "srcImageUrl": "singer-20240102/1/129529/1742047652511496192.jpg" + }, + "score": 0.7163062, + "timestamp": 1704186491979, + "deviceId": "129533", + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + }, + "objectIndex": { + "objectId": "1742110565582518272", + "solutionId": "1", + "deviceId": "129533", + "fragmentId": "0" + }, + "objectType": "OBJECT_TYPE_PEDESTRAIN", + "isObjectTrack": true, + "pathId": "1742110532019697664", + "frameInfo": { + "frameId": "0", + "frameTimestamp": "1704186491979", + "width": 0, + "height": 0, + "originWidth": 1920, + "originHeight": 1080, + "offsetTime": "24714687", + "skipNumber": "0" + }, + "level": 1, + "bboxInFrame": { + "x": 0.603125, + "y": 0.3314815, + "w": 0.0578125, + "h": 0.2712963 + }, + "bboxExtInFrame": { + "x": 0.546875, + "y": 0.2638889, + "w": 0.17135416, + "h": 0.40648147 + }, + "objectImageKey": "", + "objectExtImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565582518272.jpg", + "frameImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565603489792.jpg", + "confidence": 0.817271, + "sourceObjectId": "1742110565603489792", + "storeTimestamp": "0", + "gbNumber": "", + "qualityScore": 0, + "subObjectCount": 1, + "subObjectType": [ + "OBJECT_TYPE_FACE" + ], + "subObjectIds": [ + "1742110532015503360" + ], + "cameraInfo": { + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + } + }, + "solutionId": "1", + "fragmentId": "0", + "contrastKey": "singer-20240102/1/129533/1742110565582518272.jpg", + "compaterImages": [ + "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742047651878156288.jpg" + ], + "imgSummary": "singer-20240102/1/129533/1742110565582518272.jpg", + "imageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565582518272.jpg", + "srcImageUrl": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565603489792.jpg", + "algorithmVersion": "VERSION_REID_HEAD_ATTR", + "cameraId": "129533", + "cameraName": "4楼门口过道人脸" + }, + { + "objectId": "1742092780462684161", + "condition": { + "featureInfo": null, + "featureData": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", + "imageData": "", + "alg": "VERSION_REID_HEAD_ATTR", + "rect": { + "x": 0.271875, + "y": 0.32222223, + "w": 0.2859375, + "h": 0.67777777 + }, + "objectImageUrl": "singer-20240102/1/129529/1742047651878156288.jpg", + "srcImageUrl": "singer-20240102/1/129529/1742047652511496192.jpg" + }, + "score": 0.70154816, + "timestamp": 1704182251640, + "deviceId": "129533", + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + }, + "objectIndex": { + "objectId": "1742092780462684161", + "solutionId": "1", + "deviceId": "129533", + "fragmentId": "0" + }, + "objectType": "OBJECT_TYPE_PEDESTRAIN", + "isObjectTrack": true, + "pathId": "1742092746237163520", + "frameInfo": { + "frameId": "0", + "frameTimestamp": "1704182251640", + "width": 0, + "height": 0, + "originWidth": 1920, + "originHeight": 1080, + "offsetTime": "20474348", + "skipNumber": "0" + }, + "level": 1, + "bboxInFrame": { + "x": 0.63177085, + "y": 0.38333333, + "w": 0.078125, + "h": 0.3537037 + }, + "bboxExtInFrame": { + "x": 0.55885416, + "y": 0.29537037, + "w": 0.22447917, + "h": 0.5314815 + }, + "objectImageKey": "", + "objectExtImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092780462684161.jpg", + "frameImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092780768868352.jpg", + "confidence": 0.888334, + "sourceObjectId": "1742092780768868352", + "storeTimestamp": "0", + "gbNumber": "", + "qualityScore": 0, + "subObjectCount": 1, + "subObjectType": [ + "OBJECT_TYPE_FACE" + ], + "subObjectIds": [ + "1742092746232969217" + ], + "cameraInfo": { + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + } + }, + "solutionId": "1", + "fragmentId": "0", + "contrastKey": "singer-20240102/1/129533/1742092780462684161.jpg", + "compaterImages": [ + "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742047651878156288.jpg" + ], + "imgSummary": "singer-20240102/1/129533/1742092780462684161.jpg", + "imageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092780462684161.jpg", + "srcImageUrl": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092780768868352.jpg", + "algorithmVersion": "VERSION_REID_HEAD_ATTR", + "cameraId": "129533", + "cameraName": "4楼门口过道人脸" + }, + { + "objectId": "1742092514409592832", + "condition": { + "featureInfo": null, + "featureData": "AAAAAAAAAAAAAAA==", + "imageData": "", + "alg": "VERSION_REID_HEAD_ATTR", + "rect": { + "x": 0.271875, + "y": 0.32222223, + "w": 0.2859375, + "h": 0.67777777 + }, + "objectImageUrl": "singer-20240102/1/129529/1742047651878156288.jpg", + "srcImageUrl": "singer-20240102/1/129529/1742047652511496192.jpg" + }, + "score": 0.703765, + "timestamp": 1704182186451, + "deviceId": "129529", + "id": "129529", + "name": "4入口人脸", + "dirid": "0", + "status": "1", + "longitude": 120.12100219726562, + "latitude": 30.280099868774414, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "34", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + }, + "objectIndex": { + "objectId": "1742092514409592832", + "solutionId": "1", + "deviceId": "129529", + "fragmentId": "0" + }, + "objectType": "OBJECT_TYPE_PEDESTRAIN", + "isObjectTrack": true, + "pathId": "1742092482440607744", + "frameInfo": { + "frameId": "0", + "frameTimestamp": "1704182186451", + "width": 0, + "height": 0, + "originWidth": 2560, + "originHeight": 1440, + "offsetTime": "20409182", + "skipNumber": "0" + }, + "level": 1, + "bboxInFrame": { + "x": 0.6195313, + "y": 0.24583334, + "w": 0.09804688, + "h": 0.41944444 + }, + "bboxExtInFrame": { + "x": 0.53515625, + "y": 0.14027777, + "w": 0.26640624, + "h": 0.63125 + }, + "objectImageKey": "", + "objectExtImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092514409592832.jpg", + "frameImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092515508500480.jpg", + "confidence": 0.92494, + "sourceObjectId": "1742092515508500480", + "storeTimestamp": "0", + "gbNumber": "", + "qualityScore": 0, + "subObjectCount": 1, + "subObjectType": [ + "OBJECT_TYPE_FACE" + ], + "subObjectIds": [ + "1742092482432219136" + ], + "cameraInfo": { + "id": "129529", + "name": "4入口人脸", + "dirid": "0", + "status": "1", + "longitude": 120.12100219726562, + "latitude": 30.280099868774414, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "34", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + } + }, + "solutionId": "1", + "fragmentId": "0", + "contrastKey": "singer-20240102/1/129529/1742092514409592832.jpg", + "compaterImages": [ + "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742047651878156288.jpg" + ], + "imgSummary": "singer-20240102/1/129529/1742092514409592832.jpg", + "imageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092514409592832.jpg", + "srcImageUrl": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092515508500480.jpg", + "algorithmVersion": "VERSION_REID_HEAD_ATTR", + "cameraId": "129529", + "cameraName": "4入口人脸" + } + ], + "selectIndex": 4, + "disableBtn": [ + 0, + 1, + 4, + 20 + ], + "dataSource": [ + { + "objectId": "1742110565582518272", + "condition": { + "featureInfo": null, + "featureData": "AAAAAAAAAAAAAAAAAAAAAAA==", + "imageData": "", + "alg": "VERSION_REID_HEAD_ATTR", + "rect": { + "x": 0.271875, + "y": 0.32222223, + "w": 0.2859375, + "h": 0.67777777 + }, + "objectImageUrl": "singer-20240102/1/129529/1742047651878156288.jpg", + "srcImageUrl": "singer-20240102/1/129529/1742047652511496192.jpg" + }, + "score": 0.7163062, + "timestamp": 1704186491979, + "deviceId": "129533", + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + }, + "objectIndex": { + "objectId": "1742110565582518272", + "solutionId": "1", + "deviceId": "129533", + "fragmentId": "0" + }, + "objectType": "OBJECT_TYPE_PEDESTRAIN", + "isObjectTrack": true, + "pathId": "1742110532019697664", + "frameInfo": { + "frameId": "0", + "frameTimestamp": "1704186491979", + "width": 0, + "height": 0, + "originWidth": 1920, + "originHeight": 1080, + "offsetTime": "24714687", + "skipNumber": "0" + }, + "level": 1, + "bboxInFrame": { + "x": 0.603125, + "y": 0.3314815, + "w": 0.0578125, + "h": 0.2712963 + }, + "bboxExtInFrame": { + "x": 0.546875, + "y": 0.2638889, + "w": 0.17135416, + "h": 0.40648147 + }, + "objectImageKey": "", + "objectExtImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565582518272.jpg", + "frameImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565603489792.jpg", + "confidence": 0.817271, + "sourceObjectId": "1742110565603489792", + "storeTimestamp": "0", + "gbNumber": "", + "qualityScore": 0, + "subObjectCount": 1, + "subObjectType": [ + "OBJECT_TYPE_FACE" + ], + "subObjectIds": [ + "1742110532015503360" + ], + "cameraInfo": { + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + } + }, + "solutionId": "1", + "fragmentId": "0", + "contrastKey": "singer-20240102/1/129533/1742110565582518272.jpg", + "compaterImages": [ + "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742047651878156288.jpg" + ], + "imgSummary": "singer-20240102/1/129533/1742110565582518272.jpg", + "imageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565582518272.jpg", + "srcImageUrl": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742110565603489792.jpg", + "algorithmVersion": "VERSION_REID_HEAD_ATTR", + "cameraId": "129533", + "cameraName": "4楼门口过道人脸" + }, + { + "objectId": "1742092680994764802", + "condition": { + "featureInfo": null, + "featureData": "AAAAAAAAAAAAAAAAAAAAAAAAA==", + "imageData": "", + "alg": "VERSION_REID_HEAD_ATTR", + "rect": { + "x": 0.271875, + "y": 0.32222223, + "w": 0.2859375, + "h": 0.67777777 + }, + "objectImageUrl": "singer-20240102/1/129529/1742047651878156288.jpg", + "srcImageUrl": "singer-20240102/1/129529/1742047652511496192.jpg" + }, + "score": 0.7007122, + "timestamp": 1704182225679, + "deviceId": "129533", + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + }, + "objectIndex": { + "objectId": "1742092680994764802", + "solutionId": "1", + "deviceId": "129533", + "fragmentId": "0" + }, + "objectType": "OBJECT_TYPE_PEDESTRAIN", + "isObjectTrack": true, + "pathId": "1742092646219790337", + "frameInfo": { + "frameId": "0", + "frameTimestamp": "1704182225679", + "width": 0, + "height": 0, + "originWidth": 1920, + "originHeight": 1080, + "offsetTime": "20448387", + "skipNumber": "0" + }, + "level": 1, + "bboxInFrame": { + "x": 0.5265625, + "y": 0.49537036, + "w": 0.104166664, + "h": 0.35833332 + }, + "bboxExtInFrame": { + "x": 0.465625, + "y": 0.40648147, + "w": 0.22708334, + "h": 0.537963 + }, + "objectImageKey": "", + "objectExtImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092680994764802.jpg", + "frameImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092681720379392.jpg", + "confidence": 0.769764, + "sourceObjectId": "1742092681720379392", + "storeTimestamp": "0", + "gbNumber": "", + "qualityScore": 0, + "subObjectCount": 0, + "subObjectType": [], + "subObjectIds": [], + "cameraInfo": { + "id": "129533", + "name": "4楼门口过道人脸", + "dirid": "0", + "status": "1", + "longitude": 120.125, + "latitude": 30.280500411987305, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "38", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + } + }, + "solutionId": "1", + "fragmentId": "0", + "contrastKey": "singer-20240102/1/129533/1742092680994764802.jpg", + "compaterImages": [ + "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742047651878156288.jpg" + ], + "imgSummary": "singer-20240102/1/129533/1742092680994764802.jpg", + "imageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092680994764802.jpg", + "srcImageUrl": "http://10.0.0.7:30003/file/singer-20240102/1/129533/1742092681720379392.jpg", + "algorithmVersion": "VERSION_REID_HEAD_ATTR", + "cameraId": "129533", + "cameraName": "4楼门口过道人脸" + }, + { + "objectId": "1742092514409592832", + "condition": { + "featureInfo": null, + "featureData": "AAAAAAAAAAAAAAAAAAAAAAAA==", + "imageData": "", + "alg": "VERSION_REID_HEAD_ATTR", + "rect": { + "x": 0.271875, + "y": 0.32222223, + "w": 0.2859375, + "h": 0.67777777 + }, + "objectImageUrl": "singer-20240102/1/129529/1742047651878156288.jpg", + "srcImageUrl": "singer-20240102/1/129529/1742047652511496192.jpg" + }, + "score": 0.703765, + "timestamp": 1704182186451, + "deviceId": "129529", + "id": "129529", + "name": "4入口人脸", + "dirid": "0", + "status": "1", + "longitude": 120.12100219726562, + "latitude": 30.280099868774414, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "34", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + }, + "objectIndex": { + "objectId": "1742092514409592832", + "solutionId": "1", + "deviceId": "129529", + "fragmentId": "0" + }, + "objectType": "OBJECT_TYPE_PEDESTRAIN", + "isObjectTrack": true, + "pathId": "1742092482440607744", + "frameInfo": { + "frameId": "0", + "frameTimestamp": "1704182186451", + "width": 0, + "height": 0, + "originWidth": 2560, + "originHeight": 1440, + "offsetTime": "20409182", + "skipNumber": "0" + }, + "level": 1, + "bboxInFrame": { + "x": 0.6195313, + "y": 0.24583334, + "w": 0.09804688, + "h": 0.41944444 + }, + "bboxExtInFrame": { + "x": 0.53515625, + "y": 0.14027777, + "w": 0.26640624, + "h": 0.63125 + }, + "objectImageKey": "", + "objectExtImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092514409592832.jpg", + "frameImageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092515508500480.jpg", + "confidence": 0.92494, + "sourceObjectId": "1742092515508500480", + "storeTimestamp": "0", + "gbNumber": "", + "qualityScore": 0, + "subObjectCount": 1, + "subObjectType": [ + "OBJECT_TYPE_FACE" + ], + "subObjectIds": [ + "1742092482432219136" + ], + "cameraInfo": { + "id": "129529", + "name": "4入口人脸", + "dirid": "0", + "status": "1", + "longitude": 120.12100219726562, + "latitude": 30.280099868774414, + "caseId": "0", + "caseGroup": "", + "isDeleted": "DEVICEMANAGER_BOOL_DEFAULT", + "extendInfo": { + "vmsPlatformId": "29", + "vmsChannel": "34", + "vmsCameraDecoderTag": "hikvision", + "platformPluginType": "PLATFORM_PLUGIN_TYPE_HAIKANG_NVR", + "deviceVender": "0", + "type": "DEVICEMANAGER_CAMERA_TYPE_NORMAL", + "ip": "", + "port": "0", + "username": "", + "passwd": "", + "rtspAddress": "", + "facesnapChannel": "", + "edgeDeviceSn": "", + "platform1400Id": 0, + "useRtspAddress": false, + "frameCheck": false, + "frameRectX": 0, + "frameRectY": 0, + "frameRectW": 0, + "frameRectH": 0, + "edgeNodeId": "0", + "processStatus": "FILTER_REALTIME_DEFAULT" + } + }, + "solutionId": "1", + "fragmentId": "0", + "contrastKey": "singer-20240102/1/129529/1742092514409592832.jpg", + "compaterImages": [ + "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742047651878156288.jpg" + ], + "imgSummary": "singer-20240102/1/129529/1742092514409592832.jpg", + "imageKey": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092514409592832.jpg", + "srcImageUrl": "http://10.0.0.7:30003/file/singer-20240102/1/129529/1742092515508500480.jpg", + "algorithmVersion": "VERSION_REID_HEAD_ATTR", + "cameraId": "129529", + "cameraName": "4入口人脸" + } + ], + "isArchiveDetail": false, + "ToolProps": { + "renderVideoBtn": true, + "disableVideo": false + }, + "specialTitle": "" +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + IMAGE_DATA +}); diff --git a/packages/biz/lib/Demo/index.d.ts b/packages/biz/lib/Demo/index.d.ts new file mode 100644 index 0000000..bcc157c --- /dev/null +++ b/packages/biz/lib/Demo/index.d.ts @@ -0,0 +1,3 @@ +import React from 'react'; +declare const _default: () => React.JSX.Element; +export default _default; diff --git a/packages/biz/lib/Demo/index.js b/packages/biz/lib/Demo/index.js new file mode 100644 index 0000000..fd221c7 --- /dev/null +++ b/packages/biz/lib/Demo/index.js @@ -0,0 +1,41 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/Demo/index.tsx +var Demo_exports = {}; +__export(Demo_exports, { + default: () => Demo_default +}); +module.exports = __toCommonJS(Demo_exports); +var import_react = __toESM(require("react")); +var import_antd = require("antd"); +var import_hooks = require("@zhst/hooks"); +var Demo_default = () => { + const { run } = (0, import_hooks.useThrottleFn)(() => console.log("123")); + return /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: () => run() }, "测试"); +}; diff --git a/packages/biz/lib/adapter/BigImageModalAdapter/index.d.ts b/packages/biz/lib/adapter/BigImageModalAdapter/index.d.ts new file mode 100644 index 0000000..dab889b --- /dev/null +++ b/packages/biz/lib/adapter/BigImageModalAdapter/index.d.ts @@ -0,0 +1,153 @@ +/** + * 适配老的大屏组件数据格式传入 + */ +import React from 'react'; +import { AlgorithmVersionStr, HumanProperty, ObjectType, Rect, ViewOption, AlignType, IScreenshotButtonProp, ODRECT } from '@zhst/types'; +export type TAB_TYPE = 'COMPATER' | 'NORMAL' | 'TRACK'; +export type MODEL_TYPE = 'VIDEO' | 'IMAGE'; +export interface ImgViewProps extends React.HTMLAttributes { + imageKey: string; + odRect: ODRECT; + attachImg?: Array<{ + label: string; + url: string; + }>; + showAttachImgLabel: boolean; + screenshotButtonAlign: AlignType; + screenshotButtonRender: (screenshotButtonProp: IScreenshotButtonProp) => React.ReactElement; + scale$?: number; + showCrop$?: boolean; + hideLeftTopBtn?: boolean; + score?: number; + viewOption?: ViewOption; +} +export interface VideoViewProps { + flvUrl: string; + maxDuration?: number; + screenshotButtonAlign?: AlignType; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => React.ReactElement; + defautlNormalizationRect?: Rect; + onCropChange?: (showCrop: boolean, normalizationRect: null | Rect) => void; + showCrop$?: boolean; +} +export interface CarouselProps { + hasPre?: boolean; + hasNext?: boolean; + selectIndex: number; + setSelectIndex: React.Dispatch>; + dataSource: Array<{ + key: string; + url: string; + }>; +} +export type ISelectItem = Partial> & Partial>; +export interface HeaderProps { + value: TAB_TYPE; + onChange: (type: TAB_TYPE) => void; + tabsFilter: TAB_TYPE[]; +} +export interface ImgViewRef { + imgInsRef: React.MutableRefObject; + setShowCrop: React.Dispatch>; +} +export interface VideoViewRef { + cropAble: boolean; + setShowCrop: React.Dispatch>; + downloadVideoframe: () => void; +} +export interface ParamProps { + tab: string; + selectItem: ISelectItem; + imgViewRef: React.MutableRefObject; + VideoViewRef: React.MutableRefObject; + model: MODEL_TYPE; + setModel: React.Dispatch>; + scale$: number; + showCrop$: boolean; +} +export interface BigImageData { + extendRectList: (Rect & { + algorithmVersion: AlgorithmVersionStr; + imageKey: string; + })[]; + rectList: (Rect & { + algorithmVersion: AlgorithmVersionStr; + imageKey: string; + })[]; + attachImg: { + url: string; + label: '形体' | '人脸'; + }[]; + odRect: Rect; + imageKey: string; + imgSummary: string; + objectExtImageKey: string; + attributeList: { + label: string; + list: any[]; + }[]; + archiveImages?: any; + spaceName: string; + objectType: ObjectType; + objectId: string; + bodyObjectId?: string; + faceObjectId?: string; + sourceObjectId?: string; + cameraId: string; + cameraName: string; + selectIndex: number; + humanProperty: HumanProperty; + qualityScore?: number; + score: number; + timestamp: string; + bodyImageUrl: string; + faceImageUrl: string; + algorithmVersion: AlgorithmVersionStr; + bodySpaceName: string; + faceSpaceName: string; + solutionId?: string; + [index: string]: any; +} +interface IOldImageData { + visible?: boolean; + defaultModel?: MODEL_TYPE; + onClose?: () => void; + isLoading?: boolean; + hasPre?: boolean; + hasNext?: boolean; + selectIndex?: number; + onSelectIndexChange?: (i: number) => void; + dataSource: any[]; + dataSources: any[]; + relatedData?: any[]; + transformPropFunc: (item: any) => ISelectItem; + transformVideoPropFunc: (item: ISelectItem) => Promise>; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => React.ReactElement; + showTool?: boolean; + showCarousel?: boolean; + imgViewProp?: Partial; + videoViewProp?: Partial; + ToolProps?: Partial; + nullDialogProp?: { + emptyText?: string; + }; + showHeader?: boolean; + tabsFilter?: TAB_TYPE[]; + useVirtual?: boolean; + loadNext?: (i: number) => Promise; + loadPre?: (i: number) => Promise; + children: React.ReactNode; + title?: string; + specialTitle?: string; + isRelated?: boolean; + carouselProp?: Partial; +} +export interface ToolProps { + renderRight?: (props: ParamProps) => React.ReactNode; + renderLeft?: (props: ParamProps) => React.ReactNode; + renderVideoBtn?: boolean; + param: ParamProps; + disableVideo: boolean; +} +declare const _default: (data: IOldImageData) => IOldImageData; +export default _default; diff --git a/packages/biz/lib/adapter/BigImageModalAdapter/index.js b/packages/biz/lib/adapter/BigImageModalAdapter/index.js new file mode 100644 index 0000000..9deae88 --- /dev/null +++ b/packages/biz/lib/adapter/BigImageModalAdapter/index.js @@ -0,0 +1,28 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/adapter/BigImageModalAdapter/index.tsx +var BigImageModalAdapter_exports = {}; +__export(BigImageModalAdapter_exports, { + default: () => BigImageModalAdapter_default +}); +module.exports = __toCommonJS(BigImageModalAdapter_exports); +var BigImageModalAdapter_default = (data) => { + const newData = data; + return newData; +}; diff --git a/packages/biz/lib/adapter/index.d.ts b/packages/biz/lib/adapter/index.d.ts new file mode 100644 index 0000000..f1dd564 --- /dev/null +++ b/packages/biz/lib/adapter/index.d.ts @@ -0,0 +1 @@ +export { default as BigImageModalAdapter } from './BigImageModalAdapter'; diff --git a/packages/biz/lib/adapter/index.js b/packages/biz/lib/adapter/index.js new file mode 100644 index 0000000..8f1699d --- /dev/null +++ b/packages/biz/lib/adapter/index.js @@ -0,0 +1,39 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/adapter/index.ts +var adapter_exports = {}; +__export(adapter_exports, { + BigImageModalAdapter: () => import_BigImageModalAdapter.default +}); +module.exports = __toCommonJS(adapter_exports); +var import_BigImageModalAdapter = __toESM(require("./BigImageModalAdapter")); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BigImageModalAdapter +}); diff --git a/packages/biz/lib/hooks/useIntelligentTracking/index.d.ts b/packages/biz/lib/hooks/useIntelligentTracking/index.d.ts new file mode 100644 index 0000000..c1e54ef --- /dev/null +++ b/packages/biz/lib/hooks/useIntelligentTracking/index.d.ts @@ -0,0 +1,45 @@ +import { Dayjs as Moment } from 'dayjs'; +export declare const getDefaultRadius: () => number; +export declare const setDefaultRadius: (radius: number) => void; +export declare const setSearchIntervalDuration: (duration: number) => void; +export declare const getSearchIntervalDuration: (time: number) => number; +export declare const operateTrackById: (smartTrackId: number, operationType: OperationType) => Promise; +export declare const deleteTrackById: (smartTrackId: number) => Promise; +export declare const modifyTrackImgs: (smartTrackId: number, images: Array) => Promise; +export declare const modifyTrackConf: (conf: any, smartTrackId: number) => Promise; +export declare const getTrackTaskById: (smartTrackId?: number) => Promise; +export declare const getTackDetailInfo: (smartTrackId?: number) => Promise; +export declare const getTaskCameraByCenterAndPower: (value: { + taskPower: { + facePower: number; + bodyPower: number; + }; + cameraInfos: Array; + center: [number, number]; +}) => Promise; +/**创建追踪任务 */ +export declare const createIntelligentTrack: (value: { + images: Array; + deviceIds: Array; + circleCenter: [number, number]; + model: number; + circleRadius: number; + facePower?: number; + bodyPower?: number; + historyTime?: [Moment, Moment]; + topping?: boolean; +}) => Promise; +export declare const emitHeartbeat: (smartTrackId: number) => Promise; +export declare const ModifyTrackCameras: (value: { + smartTrackId: number; + deviceIds: Array; + centerPoint: [number, number]; +}) => Promise; +export declare const setIntelligentTrackCircleInfo: (smartTrackId: number, circleCenter: [number, number]) => Promise; +export declare const getTackCameraInfo: (value: { + circleCenter: [Moment, Moment]; + radius: number; + zoom: number; +}) => Promise; +export declare const getCameraInfoByCircle: (circleCenter: any, radius: any, zoom?: number) => Promise; +export declare const taskInfoToSearchItem: (taskInfo: any) => any[]; diff --git a/packages/biz/lib/hooks/useIntelligentTracking/index.js b/packages/biz/lib/hooks/useIntelligentTracking/index.js new file mode 100644 index 0000000..7cacace --- /dev/null +++ b/packages/biz/lib/hooks/useIntelligentTracking/index.js @@ -0,0 +1,371 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/hooks/useIntelligentTracking/index.tsx +var useIntelligentTracking_exports = {}; +__export(useIntelligentTracking_exports, { + ModifyTrackCameras: () => ModifyTrackCameras, + createIntelligentTrack: () => createIntelligentTrack, + deleteTrackById: () => deleteTrackById, + emitHeartbeat: () => emitHeartbeat, + getCameraInfoByCircle: () => getCameraInfoByCircle, + getDefaultRadius: () => getDefaultRadius, + getSearchIntervalDuration: () => getSearchIntervalDuration, + getTackCameraInfo: () => getTackCameraInfo, + getTackDetailInfo: () => getTackDetailInfo, + getTaskCameraByCenterAndPower: () => getTaskCameraByCenterAndPower, + getTrackTaskById: () => getTrackTaskById, + modifyTrackConf: () => modifyTrackConf, + modifyTrackImgs: () => modifyTrackImgs, + operateTrackById: () => operateTrackById, + setDefaultRadius: () => setDefaultRadius, + setIntelligentTrackCircleInfo: () => setIntelligentTrackCircleInfo, + setSearchIntervalDuration: () => setSearchIntervalDuration, + taskInfoToSearchItem: () => taskInfoToSearchItem +}); +module.exports = __toCommonJS(useIntelligentTracking_exports); +var turf = __toESM(require("@turf/turf")); +var import_useTaskState = require("../useTaskState"); +var import_Tree = __toESM(require("@common/components/CameraTree/Tree")); +var import_request = __toESM(require("../../utils/request")); +var import_antd = require("antd"); +var import_utils = require("@common/components/CameraTree/utils"); +var import_func = require("@zhst/func"); +var defaultFaceThreshold = 0.68; +var defaultBodyThreshold = 0.7; +var defaultFaceResultNum = 5; +var defaultRadius = 0.15; +var defaultQueryCycle = 10; +var getDefaultRadius = () => { + return defaultRadius; +}; +var setDefaultRadius = (radius) => { + defaultRadius = radius; +}; +var searchIntervalDuration = 10; +var setSearchIntervalDuration = (duration) => { + searchIntervalDuration = duration; +}; +var getSearchIntervalDuration = (time) => { + return time; +}; +var operateTrackById = async (smartTrackId, operationType) => { + try { + const data = { + operationType, + smartTrackId + }; + await (0, import_request.default)({ + method: "PUT", + url: "/singer.SmartTrackService/OperationSmartTrack", + data + }); + import_antd.message.success("操作成功"); + } catch (err) { + console.error(err); + import_antd.message.success("操作失败"); + } +}; +var deleteTrackById = async (smartTrackId) => { + try { + await (0, import_request.default)({ + method: "DELETE", + url: "/singer.SmartTrackService/DeleteSmartTrack", + data: { + smartTrackId + } + }); + } catch (err) { + console.error(err); + } +}; +var modifyTrackImgs = async (smartTrackId, images) => { + try { + await (0, import_request.default)({ + method: "PUT", + url: "/singer.SmartTrackService/ModifyTrackImg", + data: { + images, + smartTrackId + } + }); + } catch (err) { + console.log("err", err); + } +}; +var modifyTrackConf = async (conf, smartTrackId) => { + try { + await (0, import_request.default)({ + method: "PUT", + url: "/singer.SmartTrackService/ModifyTrackConf", + data: { + conf, + smartTrackId + } + }); + } catch (err) { + console.log("err", err); + } +}; +var getTrackTaskById = async (smartTrackId = 0) => { + try { + const data = smartTrackId ? { + smartTrackId + } : {}; + let req = await (0, import_request.default)({ + method: "POST", + url: "/singer.SmartTrackService/GetSmartTrack", + data + }); + return req; + } catch (err) { + console.error(err); + } +}; +var getTackDetailInfo = async (smartTrackId = 0) => { + const data = smartTrackId ? { + smartTrackId + } : {}; + let req = await (0, import_request.default)({ + method: "POST", + url: "/singer.SmartTrackService/GetTrackOverView", + data + }); + return req; +}; +var getTaskCameraByCenterAndPower = async (value) => { + let realCameraInfos = value["cameraInfos"]; + let realPreprocessInfos = []; + if (!(0, import_func.isEmpty)(realCameraInfos)) { + const { taskStatus } = await (0, import_useTaskState.getListTaskStatus)(); + realPreprocessInfos = (0, import_useTaskState.getCameraStatusFunc)(taskStatus); + } + const runRealCameraInfos = []; + realCameraInfos = realCameraInfos.filter((v) => { + if (import_Tree.default.judgeOccupyPowerById(v["id"], realPreprocessInfos)) { + runRealCameraInfos.push(v); + } + return !import_Tree.default.judgeOccupyPowerById(v["id"], realPreprocessInfos); + }); + let from = turf.point(value["center"]); + if (realCameraInfos.length > value["taskPower"]["bodyPower"]) { + realCameraInfos.map((v) => { + let dis = turf.distance(from, turf.point([v["longitude"], v["latitude"]])); + return { + ...v, + dis + }; + }).sort((a, b) => { + return a - b; + }); + realCameraInfos = realCameraInfos.slice(0, value["taskPower"]["bodyPower"]); + } + return [...runRealCameraInfos, ...realCameraInfos]; +}; +var createIntelligentTrack = async (value) => { + const data = { + images: value["images"], + type: value["model"], + normalComputerPower: value["bodyPower"] || 0, + faceComputerPower: value["facePower"] || 0, + // deviceIds: ['129537'], + deviceIds: value["deviceIds"], + conf: { + faceThreshold: defaultFaceThreshold, + bodyThreshold: defaultBodyThreshold, + faceResultNum: defaultFaceResultNum, + radius: value["circleRadius"] * 1e3, + queryCycle: defaultQueryCycle + }, + centerConf: { + centerX: value["circleCenter"][0], + centerY: value["circleCenter"][1] + } + }; + const res = await (0, import_request.default)({ + method: "PUT", + url: "/singer.SmartTrackService/CreateSmartTrack", + data + }); + return res; +}; +var emitHeartbeat = async (smartTrackId) => { + try { + await (0, import_request.default)({ + method: "POST", + url: "/singer.SmartTrackService/SmartTrackHeartBeat", + data: { + smartTrackId + } + }); + } catch (err) { + console.error(err); + } +}; +var ModifyTrackCameras = async (value) => { + try { + await setIntelligentTrackCircleInfo(value["smartTrackId"], value["centerPoint"]); + await (0, import_request.default)({ + url: "/singer.SmartTrackService/ModifyTrackCameras", + method: "PUT", + data: { + smartTrackId: value["smartTrackId"], + deviceIds: value["deviceIds"] + } + }); + } catch (err) { + import_antd.message.error(err); + } +}; +var setIntelligentTrackCircleInfo = async (smartTrackId, circleCenter) => { + try { + await (0, import_request.default)({ + url: "/singer.SmartTrackService/ModifyTrackScopeConf", + method: "PUT", + data: { + smartTrackId, + centerConf: { + centerX: (0, import_func.get)(circleCenter, "0"), + centerY: (0, import_func.get)(circleCenter, "1") + } + } + }); + } catch (err) { + import_antd.message.error(err); + } +}; +var getTackCameraInfo = async (value) => { + let circleCameraInfos = await getCameraInfoByCircle( + value["circleCenter"], + value["radius"], + value["zoom"] + ); + return circleCameraInfos; +}; +var getCameraInfoByCircle = async (circleCenter, radius, zoom = 16) => { + try { + let centerFeature = turf.circle(turf.point(circleCenter), radius, { + units: "kilometers", + steps: 64 + }); + let minx = 0; + let maxx = 0; + let miny = 0; + let maxy = 0; + for (let i = 0; i < 4; i++) { + let point2 = turf.destination(turf.point(circleCenter), radius, 90 * i, { + units: "kilometers" + }).geometry.coordinates; + if (point2[0] < minx || minx === 0) { + minx = point2[0]; + } + if (point2[0] > maxx || maxx === 0) { + maxx = point2[0]; + } + if (point2[1] < miny || miny === 0) { + miny = point2[1]; + } + if (point2[1] > maxy || maxy === 0) { + maxy = point2[1]; + } + } + let { clusterPoint } = await (0, import_request.default)({ + url: "/singer.DeviceService/GetClusters", + method: "POST", + data: { + northEast: { X: maxx, Y: maxy }, + southWest: { X: minx, Y: miny }, + zoom + } + }); + let cameraIds = []; + clusterPoint.forEach((v) => { + cameraIds.push(...v["cameraIDs"]); + }); + const { cameras } = await (0, import_utils.SearchCamera)({ + cameraId: cameraIds, + maxResults: cameraIds.length + }); + const cameraInfos = cameras.filter((v) => { + let cameraPoint = turf.point([(0, import_func.get)(v, "longitude"), (0, import_func.get)(v, "latitude")]); + return turf.booleanPointInPolygon(cameraPoint, centerFeature); + }); + return cameraInfos; + } catch (err) { + console.error(err); + return []; + } +}; +var taskInfoToSearchItem = (taskInfo) => { + let imageList = []; + (0, import_func.get)(taskInfo, "images", []).forEach((v) => { + const url = (0, import_func.get)(v, "conds.0.srcImageUrl"); + const objectId = (0, import_func.get)(v, "conds.0.featureInfo.objectId"); + let imageItem = { + index: 0, + url, + objectId, + odRects: (0, import_func.get)(v, "conds").map((item) => { + return { + fileKey: (0, import_func.get)(item, "objectImageUrl"), + extendRect: { + algorithmVersion: (0, import_func.get)(item, "alg", ""), + ...(0, import_func.get)(item, "rect", {}) + }, + rect: { + algorithmVersion: (0, import_func.get)(item, "alg", ""), + rect: (0, import_func.get)(item, "rect", {}) + } + }; + }) + }; + imageList.push(imageItem); + }); + return imageList; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ModifyTrackCameras, + createIntelligentTrack, + deleteTrackById, + emitHeartbeat, + getCameraInfoByCircle, + getDefaultRadius, + getSearchIntervalDuration, + getTackCameraInfo, + getTackDetailInfo, + getTaskCameraByCenterAndPower, + getTrackTaskById, + modifyTrackConf, + modifyTrackImgs, + operateTrackById, + setDefaultRadius, + setIntelligentTrackCircleInfo, + setSearchIntervalDuration, + taskInfoToSearchItem +}); diff --git a/packages/biz/lib/index.d.ts b/packages/biz/lib/index.d.ts new file mode 100644 index 0000000..ac47c74 --- /dev/null +++ b/packages/biz/lib/index.d.ts @@ -0,0 +1,3 @@ +export { default as Demo } from './Demo'; +export * from './adapter'; +export { default as BigImageModal } from './BigImageModal'; diff --git a/packages/biz/lib/index.js b/packages/biz/lib/index.js new file mode 100644 index 0000000..85c051d --- /dev/null +++ b/packages/biz/lib/index.js @@ -0,0 +1,45 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.tsx +var src_exports = {}; +__export(src_exports, { + BigImageModal: () => import_BigImageModal.default, + Demo: () => import_Demo.default +}); +module.exports = __toCommonJS(src_exports); +var import_Demo = __toESM(require("./Demo")); +__reExport(src_exports, require("./adapter"), module.exports); +var import_BigImageModal = __toESM(require("./BigImageModal")); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BigImageModal, + Demo, + ...require("./adapter") +}); diff --git a/packages/biz/lib/useSocket/index.d.ts b/packages/biz/lib/useSocket/index.d.ts new file mode 100644 index 0000000..08018b5 --- /dev/null +++ b/packages/biz/lib/useSocket/index.d.ts @@ -0,0 +1,26 @@ +export declare const SocketApi: { + CameraTaskStatue: string; + DeviceStatus: string; + SubscribeSolutionDeploy: string; + SubscribeTasksSummary: string; + MonitorSubscribeResult: string; + MonitorSubscribeStatus: string; + SubscribeArchiveGroupUpload: string; + SubscribeJointTask: string; + SubscribeGroupFragment: string; + SubscribeGroup: string; + SubscribeStreamEvent: string; +}; +type ApiKeys = keyof typeof SocketApi; +declare const _default: (topic: ApiKeys, iterator?: any, opt?: { + req?: { + [key: string]: any; + } | undefined; + throttle?: number | undefined; + parseData?: boolean | undefined; + beforeLoopTmp?: Function | undefined; + shouldBreak: boolean; + forceRefresh: any; + close?: boolean | undefined; +} | undefined) => void; +export default _default; diff --git a/packages/biz/lib/useSocket/index.js b/packages/biz/lib/useSocket/index.js new file mode 100644 index 0000000..f7a3435 --- /dev/null +++ b/packages/biz/lib/useSocket/index.js @@ -0,0 +1,120 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/useSocket/index.ts +var useSocket_exports = {}; +__export(useSocket_exports, { + SocketApi: () => SocketApi, + default: () => useSocket_default +}); +module.exports = __toCommonJS(useSocket_exports); +var import_react = require("react"); +var import_func = require("@zhst/func"); +var import_hooks = require("@zhst/hooks"); +var import_ws = __toESM(require("./ws")); +var noop = (v) => null; +var getSelf = (v) => v; +var SocketApi = { + CameraTaskStatue: "singer.DeviceService/SubScribeCameraTaskStatus", + DeviceStatus: "singer.TaskManagerService/SubscribeTaskStatus", + SubscribeSolutionDeploy: "singer.SolutionManagerService/SubscribeSolutionDeploy", + SubscribeTasksSummary: "singer.TaskManagerService/SubscribeTasksSummary", + MonitorSubscribeResult: "singer.MonitorService/MonitorSubscribeResult", + MonitorSubscribeStatus: "singer.MonitorService/MonitorSubscribeStatus", + SubscribeArchiveGroupUpload: "singer.ArchiveGroupService/CreateArchiveByImport", + SubscribeJointTask: "singer.JointTaskService/SubscribeJointTask", + SubscribeGroupFragment: "singer.VideoService/SubscribeVideoFragmentStatus", + // 监听视频分片状态变化,包括新建、删除、变化 + SubscribeGroup: "singer.VideoService/SubscribeGroup", + // 监听视频分组状态变化,列表变化也通知 + SubscribeStreamEvent: "singer.MediaManagerService/SubscribeStreamEvent" + // 监听视频分组状态变化,列表变化也通知 +}; +var useSocket_default = (topic, iterator = noop, opt) => { + const { + req = {}, + throttle = 0, + parseData = true, + beforeLoopTmp = getSelf, + shouldBreak = false, + forceRefresh, + close + } = opt || {}; + const reqstring = (0, import_react.useMemo)(() => { + const newReq = { + ...req, + extraHeaders: { + authorization: localStorage.getItem("USER-TOKEN") + } + }; + return JSON.stringify(newReq); + }, [req]); + const latestIterator = (0, import_hooks.useLatest)(iterator); + (0, import_hooks.useDeepEffect)(() => { + if (close) { + return; + } + if (shouldBreak) { + return; + } + let tmpData = []; + const throttleUpdate = (0, import_func.throttle)(() => { + if (tmpData.length == 0) { + return; + } + const _tmpData = beforeLoopTmp(tmpData); + latestIterator.current(_tmpData); + tmpData = []; + }, throttle); + const unSubscribe = import_ws.default.subscribe(SocketApi[topic], reqstring, (socketData) => { + try { + if (!throttle) { + latestIterator.current(socketData); + } else { + tmpData.push(socketData); + throttleUpdate(); + } + } catch (error) { + console.error("useSocke:", error); + } + }); + return () => { + try { + unSubscribe(); + throttleUpdate.cancel(); + } catch (error) { + console.error(error); + throw error; + } + }; + }, [topic, reqstring, shouldBreak, forceRefresh, close]); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + SocketApi +}); diff --git a/packages/biz/lib/useSocket/onceChannel.d.ts b/packages/biz/lib/useSocket/onceChannel.d.ts new file mode 100644 index 0000000..400ffa7 --- /dev/null +++ b/packages/biz/lib/useSocket/onceChannel.d.ts @@ -0,0 +1,2 @@ +declare const startChannel: (topic: any, req: any, callback: any) => () => void; +export default startChannel; diff --git a/packages/biz/lib/useSocket/onceChannel.js b/packages/biz/lib/useSocket/onceChannel.js new file mode 100644 index 0000000..2dc648e --- /dev/null +++ b/packages/biz/lib/useSocket/onceChannel.js @@ -0,0 +1,51 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/useSocket/onceChannel.tsx +var onceChannel_exports = {}; +__export(onceChannel_exports, { + default: () => onceChannel_default +}); +module.exports = __toCommonJS(onceChannel_exports); +var import_ws = __toESM(require("./ws")); +var startChannel = (topic, req, callback) => { + let reqstring = JSON.stringify({ + ...req, + extraHeaders: { + authorization: localStorage.getItem("USER-TOKEN") + } + }); + let unSubscribe = import_ws.default.subscribe(topic, reqstring, (socketData) => { + let shouldStop = callback(socketData); + if (shouldStop) { + unSubscribe == null ? void 0 : unSubscribe(); + } + }); + return unSubscribe; +}; +var onceChannel_default = startChannel; diff --git a/packages/biz/lib/useSocket/ws.d.ts b/packages/biz/lib/useSocket/ws.d.ts new file mode 100644 index 0000000..cb4f172 --- /dev/null +++ b/packages/biz/lib/useSocket/ws.d.ts @@ -0,0 +1,31 @@ +/// +/// +/// +/// +/// +declare class Channel { + /** + * io 实例化对象 + */ + ioIns: any; + /** + * 已存在的订阅列表 + */ + listeners: never[]; + /** + * 调试信息 记录订阅/反订阅次数 + */ + subscribeListenerId: never[]; + unSubscribeListenerId: never[]; + init: () => void; + retry: (listener: { + [x: string]: any; + lastRetryInterval: number | undefined; + intervalId: NodeJS.Timeout; + } | undefined) => void; + doEmit: (topic: any, req: any, listenerId: any) => void; + subscribe(topic: any, req: any, handle: any): () => void; + unSubscribe(topic: any, req: any, handleId: any, listenerId: any): void; +} +declare const channelIns: Channel; +export default channelIns; diff --git a/packages/biz/lib/useSocket/ws.js b/packages/biz/lib/useSocket/ws.js new file mode 100644 index 0000000..8dab6f2 --- /dev/null +++ b/packages/biz/lib/useSocket/ws.js @@ -0,0 +1,224 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/useSocket/ws.ts +var ws_exports = {}; +__export(ws_exports, { + default: () => ws_default +}); +module.exports = __toCommonJS(ws_exports); +var import_uuid = require("uuid"); +var import_func = require("@zhst/func"); +var import_socket = __toESM(require("socket.io-client")); +var import_constants = require("@common/constants"); +var EMITSTATE = { + NOT_CONNECT: 0, + WAITING: 1, + CONNECT: 2 +}; +var initRetryTime = 0; +var intervalTime = 5 * 1e3; +var maxIntervalTime = 1 * 60 * 60 * 1e3; +var Channel = class { + constructor() { + /** + * 已存在的订阅列表 + */ + this.listeners = [ + // { + // topic: "", + // req: "", + // suInfo: {}, + // hasEmit: false,//是否已经订阅 + // lastRetryInterval: 0, + // handles: { + // } + // } + ]; + /** + * 调试信息 记录订阅/反订阅次数 + */ + this.subscribeListenerId = []; + this.unSubscribeListenerId = []; + this.init = () => { + const ioIns = this.ioIns = (0, import_socket.default)(import_constants.SOCKET_HOST, { + reconnection: true, + transports: ["websocket"], + forceNew: true + }); + ioIns.on("connect", (...arg) => { + console.debug("connect", arg); + this.ioIns = ioIns; + this.listeners.forEach((v) => { + this.doEmit(v["topic"], v["req"], v["id"]); + }); + }); + ioIns.on("event", (...arg) => { + console.debug("event", arg); + }); + ioIns.on("disconnect", (...arg) => { + console.debug("disconnect", arg); + this.subscribeListenerId = []; + this.unSubscribeListenerId = []; + }); + ioIns.on("reconnect", (...arg) => { + console.debug("reconnect", arg); + this.listeners.forEach((v) => { + v["hasEmit"] = EMITSTATE.NOT_CONNECT; + this.doEmit(v["topic"], v["req"], v["id"]); + }); + }); + }; + this.retry = (listener) => { + const intervalId = setTimeout(() => { + const hasExit = this.listeners.find( + (v) => v["topic"] === (listener == null ? void 0 : listener["topic"]) && v["req"] === listener["req"] + ); + if (!hasExit) + return; + listener["hasEmit"] = EMITSTATE.NOT_CONNECT; + this.doEmit(listener["topic"], listener["req"], listener["id"]); + }, listener.lastRetryInterval); + listener.intervalId = intervalId; + listener.lastRetryInterval = intervalTime + listener.lastRetryInterval > maxIntervalTime ? maxIntervalTime : intervalTime + listener.lastRetryInterval; + }; + this.doEmit = (topic, req, listenerId) => { + var _a, _b; + if (!this.ioIns) { + this.init(); + } + const hasEmit = this.listeners.find( + (v) => v["topic"] === topic && v["req"] === req && v["hasEmit"] !== EMITSTATE.NOT_CONNECT + ); + if (hasEmit) { + return; + } + const listener = this.listeners.find((v) => v["topic"] === topic && v["req"] === req); + listener["hasEmit"] = EMITSTATE.WAITING; + (_b = (_a = this.ioIns) == null ? void 0 : _a.emit) == null ? void 0 : _b.call(_a, topic, req, (data) => { + var _a2, _b2; + console.info("emit", topic, req, data); + const suInfo = JSON.parse(data); + if ((0, import_func.has)(suInfo, "Error.code")) { + if (suInfo.Error.code === 500) { + this.retry(listener); + } + return; + } + this.subscribeListenerId.push(listenerId); + const currentTopicIndex = this.listeners.findIndex( + (v) => v["topic"] === topic && v["req"] === req && v["id"] === listenerId + ); + if (currentTopicIndex == -1) { + this.ioIns.emit("UnSubscribe", JSON.stringify(suInfo), (data2) => { + this.unSubscribeListenerId.push(listenerId); + console.debug("UNSUBSCRIBE", listenerId, topic, req, data2); + }); + return; + } + if (!suInfo["SubscribeID"]) { + this.listeners.splice(currentTopicIndex, 0); + } else { + this.listeners[currentTopicIndex]["suInfo"] = suInfo; + this.listeners[currentTopicIndex]["hasEmit"] = EMITSTATE.CONNECT; + } + (_b2 = (_a2 = this.ioIns) == null ? void 0 : _a2.on) == null ? void 0 : _b2.call(_a2, suInfo["SubscribeID"], (data2) => { + console.info("on", suInfo["SubscribeID"], data2); + try { + const socketData = JSON.parse(data2); + if ((0, import_func.has)(socketData, "Error.code")) { + if (socketData.Error.code === 500) { + this.retry(listener); + } + return; + } + const { handles = {} } = this.listeners.find((v) => v["topic"] === topic && v["req"] === req) || {}; + Object.keys(handles).forEach((key) => { + try { + const func = handles[key]; + if (!func) + return; + func(socketData); + } catch (error) { + console.error(error); + } + }); + } catch (error) { + console.debug("error", error); + } + }); + }); + }; + } + subscribe(topic, req, handle) { + const handleId = (0, import_uuid.v4)(); + const listenerId = (0, import_uuid.v4)(); + const listener = this.listeners.find((v) => v["topic"] === topic && v["req"] === req); + if (listener) { + listener["handles"][handleId] = handle; + } else { + this.listeners.push({ + topic, + req, + suInfo: {}, + id: listenerId, + hasEmit: EMITSTATE.NOT_CONNECT, + lastRetryInterval: initRetryTime, + handles: { + [`${handleId}`]: handle + } + }); + this.doEmit(topic, req, listenerId); + } + return this.unSubscribe.bind(this, topic, req, handleId, listenerId); + } + unSubscribe(topic, req, handleId, listenerId) { + const listener = this.listeners.find( + (v) => v["topic"] === topic && v["req"] === req && v["id"] === listenerId + ); + const { handles = {}, suInfo } = listener || {}; + if (handles[handleId]) { + delete handles[handleId]; + if (Object.keys(handles).length === 0) { + if (this.intervalId) { + clearTimeout(this.intervalId); + } + if (listener["hasEmit"] === EMITSTATE["CONNECT"]) { + this.ioIns.emit("UnSubscribe", JSON.stringify(suInfo), (data) => { + this.unSubscribeListenerId.push(listenerId); + console.debug("UNSUBSCRIBE", listener["id"], topic, req, data); + }); + } + this.listeners = this.listeners.filter((v) => !(v["topic"] === topic && v["req"] === req)); + } + } + } +}; +var channelIns = new Channel(); +window.__channel__ = channelIns; +var ws_default = channelIns; diff --git a/packages/biz/lib/utils/constants.d.ts b/packages/biz/lib/utils/constants.d.ts new file mode 100644 index 0000000..45a9a99 --- /dev/null +++ b/packages/biz/lib/utils/constants.d.ts @@ -0,0 +1,23 @@ +export declare const OBJECT_GRNER_THRESHOLD = 0.8; +export declare const OBJECT_AGE_TYPE_THRESHOLD = 0.5; +export declare const MODE_KEY = "test_mode"; +export declare const SEARCH_IMG_COUNT = 10; +export declare const GLOBAL_IS_ITEM_NUMBER_SHOW = false; +export declare const publicPath = "hummingbird"; +export declare const ENTER_CIRCLE = "MONITORTYPE_ENTER_CIRCLE"; +export declare const OUT_CIRCLE = "MONITORTYPE_OUT_CIRCLE"; +export declare const TEMP = "MONITORTYPE_TEMP"; +export declare const GLOBAL_IS_BOX_VMS_SHOW = true; +export declare const BODY_SEARCH_THRESHOID = 0.45; +export declare const RECORD_VERSION = "3.0.0"; +export declare const DeviceTab: { + EMPTY: number; + REAL_CAMERA: number; + PREPROCESS_CAMERA: number; + TAG_CAMERA: number; + HISTORY_VIDEO_GROUP: number; + VIRTUAL_CAMERA: number; + REAL_CAMERA_NOFACE: number; + REAL_CAMERA_ONLYFACE: number; + REAL_CAMERA_NOFACE_NOBOX_NODIRECONNECT: number; +}; diff --git a/packages/biz/lib/utils/constants.js b/packages/biz/lib/utils/constants.js new file mode 100644 index 0000000..6c57f12 --- /dev/null +++ b/packages/biz/lib/utils/constants.js @@ -0,0 +1,80 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils/constants.ts +var constants_exports = {}; +__export(constants_exports, { + BODY_SEARCH_THRESHOID: () => BODY_SEARCH_THRESHOID, + DeviceTab: () => DeviceTab, + ENTER_CIRCLE: () => ENTER_CIRCLE, + GLOBAL_IS_BOX_VMS_SHOW: () => GLOBAL_IS_BOX_VMS_SHOW, + GLOBAL_IS_ITEM_NUMBER_SHOW: () => GLOBAL_IS_ITEM_NUMBER_SHOW, + MODE_KEY: () => MODE_KEY, + OBJECT_AGE_TYPE_THRESHOLD: () => OBJECT_AGE_TYPE_THRESHOLD, + OBJECT_GRNER_THRESHOLD: () => OBJECT_GRNER_THRESHOLD, + OUT_CIRCLE: () => OUT_CIRCLE, + RECORD_VERSION: () => RECORD_VERSION, + SEARCH_IMG_COUNT: () => SEARCH_IMG_COUNT, + TEMP: () => TEMP, + publicPath: () => publicPath +}); +module.exports = __toCommonJS(constants_exports); +var OBJECT_GRNER_THRESHOLD = 0.8; +var OBJECT_AGE_TYPE_THRESHOLD = 0.5; +var MODE_KEY = "test_mode"; +var SEARCH_IMG_COUNT = 10; +var GLOBAL_IS_ITEM_NUMBER_SHOW = false; +var publicPath = "hummingbird"; +var ENTER_CIRCLE = "MONITORTYPE_ENTER_CIRCLE"; +var OUT_CIRCLE = "MONITORTYPE_OUT_CIRCLE"; +var TEMP = "MONITORTYPE_TEMP"; +var GLOBAL_IS_BOX_VMS_SHOW = true; +var BODY_SEARCH_THRESHOID = 0.45; +var RECORD_VERSION = "3.0.0"; +var DeviceTab = { + EMPTY: 0, + REAL_CAMERA: 1, + PREPROCESS_CAMERA: 2, + //摄像头列表 + TAG_CAMERA: 3, + //预案列表 + HISTORY_VIDEO_GROUP: 4, + //录像回放 + VIRTUAL_CAMERA: 5, + //离线视频 + REAL_CAMERA_NOFACE: 6, + REAL_CAMERA_ONLYFACE: 7, + REAL_CAMERA_NOFACE_NOBOX_NODIRECONNECT: 8 + // 只有普通摄像头,没有人脸、没有盒子、直连 +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BODY_SEARCH_THRESHOID, + DeviceTab, + ENTER_CIRCLE, + GLOBAL_IS_BOX_VMS_SHOW, + GLOBAL_IS_ITEM_NUMBER_SHOW, + MODE_KEY, + OBJECT_AGE_TYPE_THRESHOLD, + OBJECT_GRNER_THRESHOLD, + OUT_CIRCLE, + RECORD_VERSION, + SEARCH_IMG_COUNT, + TEMP, + publicPath +}); diff --git a/packages/hooks/es/useIMEComposition/constants.d.ts b/packages/biz/lib/utils/index.d.ts similarity index 100% rename from packages/hooks/es/useIMEComposition/constants.d.ts rename to packages/biz/lib/utils/index.d.ts diff --git a/packages/hooks/es/useIMEComposition/constants.js b/packages/biz/lib/utils/index.js similarity index 100% rename from packages/hooks/es/useIMEComposition/constants.js rename to packages/biz/lib/utils/index.js diff --git a/packages/biz/package.json b/packages/biz/package.json index 856a801..8508710 100644 --- a/packages/biz/package.json +++ b/packages/biz/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/biz", - "version": "0.2.4", + "version": "0.3.0", "description": "业务库", "keywords": [ "business", @@ -40,9 +40,7 @@ "@zhst/hooks": "workspace:^", "@zhst/meta": "workspace:^", "antd": "^5.12.5", - "base-64": "^1.0.0", "classnames": "^2.5.1", - "rc-util": "^5.38.1", - "umi-request": "^1.4.0" + "rc-util": "^5.38.1" } } diff --git a/packages/biz/src/BigImageModal/BigImageModal.tsx b/packages/biz/src/BigImageModal/BigImageModal.tsx new file mode 100644 index 0000000..28ae31c --- /dev/null +++ b/packages/biz/src/BigImageModal/BigImageModal.tsx @@ -0,0 +1,162 @@ +// @ts-nocheck +import React, { useRef, useState } from 'react' +import { Descriptions, Modal, Tabs } from 'antd'; +import classNames from 'classnames' +import type { ModalProps, DescriptionsProps, TabsProps } from 'antd' +import { get } from '@zhst/func'; +import './index.less' +import Navigation from './components/navigation'; + +const DescriptionsItem = Descriptions.Item + +export const componentPrefix = 'zhst-image' + +export interface BigImageModalProps extends ModalProps { + visible: boolean // 弹框显示隐藏 + descriptionConfig: { + data: { // 描述列表 + title: string; // 标题 + children: Pick // 描述项 + }[] + } + tabsConfig: { // 导航栏配置 + data: Pick & { + key: 'NORMAL' | 'COMPATER' | 'TRACK' + } // 导航栏列表 + } + dataSource: any + imageData: any + relatedData: any +} + +const initialStyle ={ + fontSize: '12px' +} + +const BigImageModal: React.FC = (props) => { + const { + title = '-', + open, + visible, + children, + descriptionConfig = { + data: [] + }, + tabsConfig = { + data: [ + { + label: '对比图模式', + key: '1', + children: '对比图组件', + }, + { + label: '场景图模式', + key: '2', + children: '场景图组件', + } + ], + }, + dataSource = [], + imageData = [], + relatedData = [], + } = props + + const showCropRef = useRef(false); + const scaleRef = useRef(0); + + // ========================== 头切换 ========================= + const [activeKey, setActiveKey] = useState(get(tabsConfig, 'data[0].key')); + + // ========================= 预览切换下标 ========================= + const [previewIndex, setPreviewIndex] = useState(0) + const [isRelated, setIsRelated] = useState(false) + + return ( + + {descriptionConfig.data.map(descriptions => ( + + {descriptions.title} +

    + } + column={8} + style={{ padding: '0 64px' }} + > + {descriptions?.children?.map(item => ( + {item.children} + ))} +
    + ))} + +
    + { + activeKey !== 'TRACK' && ( + <> + {/* ----------------------------------- 上一张按钮 ---------------------------------- */} + 1) : (dataSource.length > 1)} + disabled={previewIndex <= 0} + prev + onClick={() => { + setPreviewIndex((pre) => pre - 1); + }} + /> + {/* ----------------------------------- 下一张按钮 ---------------------------------- */} + = imageData.length - 1) || (previewIndex >= dataSource.length - 1)) && `${componentPrefix}-view-container__nav--disabled`, + `${componentPrefix}-view-container__nav--right` + )} + show={isRelated ? (imageData.length > 1) : (dataSource.length > 1)} + disabled={((previewIndex >= imageData.length - 1) || (previewIndex >= dataSource.length - 1))} + next + onClick={async (e) => { + setPreviewIndex((pre) => pre + 1); + }} + /> + + ) + } +
    +
    + ) +} + +export default BigImageModal diff --git a/packages/biz/src/BigImageModal/index.temp.tsx b/packages/biz/src/BigImageModal/index.temp.tsx deleted file mode 100644 index 0e861cc..0000000 --- a/packages/biz/src/BigImageModal/index.temp.tsx +++ /dev/null @@ -1,696 +0,0 @@ -// @ts-nocheck -import React, { ReactElement, useEffect, useRef, useState, useMemo } from 'react'; -import { useLatest, useThrottleFn } from 'ahooks'; -import { isFunction, pick, noop, get, isEmpty } from 'lodash-es'; -import classNames from 'classnames'; -import { message, Modal, Tabs as TabPane } from 'antd'; -import KeyCode from 'rc-util/lib/KeyCode'; -import { observer } from 'mobx-react-lite'; -import ImgView, { ImgViewProps, ImgViewRef } from './ImgView'; -import VideoView, { VideoViewProps, VideoViewRef } from './VideoView'; -import CompareView from './CompareView'; -import Tool, { ToolProps } from './Tool'; -import Header, { Tabs, TabsType, tabsFilter } from './Header'; -import Navigation from './Nav'; -import AttributePanel from './AttributePanel'; -import { usePropState, cssPrefix, getSolt } from './utils'; -import { screenshotButtonProp, MODEL_TYPE, Rect } from '../adapter/BigImageModalAdapter/interface'; -import NullView, { NullDialogProp } from './NullDialog'; -import styles from './index.module.scss'; -import { generateImg } from '@common/utils'; -import IconFont from '../iconfont/IconFont'; -import addEventListenerWrap from '@common/utils/addEventListener'; -import Carousel, { CarouselProps } from './Carousel'; -import { doubleClick } from '@common/components/doubleCheck'; -import { store } from '@store/index'; -import { store as achieveStore } from '@pages/archive/store'; -import { ObjectType } from '@store/Monitor'; - -const componentName = cssPrefix; - -export type selecItem = Partial> & - Partial>; - -export interface ParamProps { - tab: string; - selectItem: selecItem; - imgViewRef: React.MutableRefObject; - VideoViewRef: React.MutableRefObject; - model: MODEL_TYPE; - setModel: React.Dispatch>; - /* 可观测值 */ - scale$: number; - showCrop$: boolean; -} - -export interface BigImageData { - //imageKey 小图 - extendRectList: (Rect & { algorithmVersion: AlgorithmVersionStr; imageKey: string })[]; - rectList: (Rect & { algorithmVersion: AlgorithmVersionStr; imageKey: string })[]; - attachImg: { url: string; label: '形体' | '人脸' }[]; - odRect: Rect; - imageKey: string; //大图 - imgSummary: string; //摘要图 - - objectExtImageKey: string; //比对到的目标图扩展图 === imgSummary - attributeList: { label: string; list: any[] }[]; - archiveImages?: any; - spaceName: string; - - objectType: ObjectType; - objectId: string; //这张摘要本身的Id - bodyObjectId?: string; - faceObjectId?: string; //这张摘要下的人脸Id(如果有) - sourceObjectId?: string; //这张摘要上游的形体Id(如果有) - cameraId: string; - cameraName: string; - selectIndex: number; - humanProperty: HumanProperty; - qualityScore?: number; //人脸质量分 - score: number; //相似度 - timestamp: string; - bodyImageUrl: string; - faceImageUrl: string; - algorithmVersion: AlgorithmVersionStr; - - bodySpaceName: string; - faceSpaceName: string; - - solutionId?: Solution; - [index: string]: any; -} - -export interface BigImageDialogProps { - visible?: boolean; - defaultModel?: MODEL_TYPE; - onClose?: () => void; - isLoading?: boolean; - hasPre?: boolean; - hasNext?: boolean; - selectIndex?: number; - onSelectIndexChange?: (index: number) => void; - dataSource: any[]; - relatedData?: any[]; - transformPropFunc: (item: any) => selecItem; - transformVideoPropFunc: ( - item: selecItem - ) => Promise>; - screenshotButtonRender?: (screenshotButtonProp: screenshotButtonProp) => ReactElement; - showTool?: boolean; - showCarousel?: boolean; - imgViewProp?: Partial; - videoViewProp?: Partial; - ToolProps?: Partial; - nullDialogProp?: Partial; - showHeader?: boolean; - tabsFilter?: tabsFilter; - useVirtual?: boolean; - loadNext?: (index: number) => Promise; - loadPre?: (index: number) => Promise; - children: React.ReactNode; - title?: string; - specialTitle?: string; - isRelated?: boolean; - carouselProp?: Partial; -} - -//查看对比图和场景图组件 -const BigImageDialog: React.FC = (props) => { - const { - hasPre: propHasPre = false, - hasNext: propHasNext = false, - loadNext = noop, - loadPre = noop, - visible = true, - onClose, - isLoading: propIsLoading = false, - selectIndex: propSelectIndex = 0, - onSelectIndexChange, - dataSource = [], - relatedData = [], - screenshotButtonRender, - transformPropFunc, - transformVideoPropFunc, - defaultModel = 'IMAGE', - imgViewProp: otherImgViewProp, - videoViewProp: otherVideoViewProp, - carouselProp: otherCarouselProp, - ToolProps: otherToolProp, - showTool = true, - children, - nullDialogProp, - showHeader = true, - tabsFilter = ['COMPATER', 'NORMAL'], - useVirtual, - title = '查看大图', - specialTitle = '', - showCarousel = true, - isRelated = false, - } = props; - - console.log('props', props) - //可观测值 - const showCrop$Ref = useRef(false); - const scale$Ref = useRef(0); - const showCrop$ = showCrop$Ref.current; - const scale$ = scale$Ref.current; - // ========================== 头切换 ========================= - const [tab, setTab] = useState( - tabsFilter.length > 1 ? (Object.keys(Tabs)[0] as TAB_TYPE) : (Object.keys(Tabs)[1] as TAB_TYPE) - ); - const [activeKey, setActiveKey] = useState('related'); - const [similarList, setSimilarList] = useState(dataSource); // 其他相似目标列表 - const [relatedList, setRelatedList] = useState(relatedData); // 已关联列表 - const [imageData, setImageData] = useState(dataSource); // 其他相似目标列表 - const lastSimData = useLatest(similarList); - const lastRelatedData = useLatest(relatedList); - - // ========================== 内部转换 ========================= - const [model, setModel] = useState(defaultModel); // 图片/视频模式 - useEffect(() => { - if (activeKey === 'unRlated') { - setImageData(lastSimData.current); - setSelectIndex(0); - } - if (activeKey === 'related') { - setImageData(lastRelatedData.current); - setSelectIndex(0); - } - }, [activeKey]); - useEffect(() => { - setSimilarList(dataSource); - if (activeKey === 'unRelated') { - setImageData(dataSource); - } - }, [dataSource]); - - const carouseDataSource = useMemo(() => { - return imageData.map((v: any, index: number) => { - return { - url: generateImg(get(v, 'passerbyImage.objectRects.0.fileKey')), - key: index, - passerbyId: get(v, 'passerbyId'), - }; - }); - }, [imageData, dataSource]); - - //选择 - const [selectIndex, setSelectIndex] = usePropState(propSelectIndex); - const hasPre = propHasPre ? true : selectIndex > 0; - const changeIndex = isRelated ? imageData.length - 1 : dataSource.length - 1; - const hasNext = propHasNext ? true : selectIndex < changeIndex; - //设置选中 - const latestSelectIndex = useLatest(selectIndex); - const latestDataSource = isRelated ? useLatest(imageData) : useLatest(dataSource); - //加一个防背推 - const seq = useRef(0); - const { run: setSelectIndexWrapper } = useThrottleFn( - async (arg: ((num: number) => void) | number) => { - const _seq = ++seq.current; - const selectIndex = latestSelectIndex.current; - const dataSource = latestDataSource.current; - let newIndex = isFunction(arg) ? arg(selectIndex) : arg; - if (newIndex > dataSource.length - 1) { - if (propHasNext) { - await loadNext(newIndex); - } else { - newIndex = dataSource.length - 1; - } - } - if (newIndex < 0) { - newIndex = 0; - } - if (_seq !== seq.current) { - return; - } - - onSelectIndexChange && onSelectIndexChange(newIndex); - setSelectIndex(newIndex); - }, - { wait: 500 } - ); - - //异步获取数据 - const [selectItem, setSelectItem] = useState(null); - const [isFetching, setIsFetching] = useState(true); - //人员属性 - const [attributeList, setAttributeList] = useState([]); - const isLoading = useMemo(() => propIsLoading || isFetching, [propIsLoading, isFetching]); - useEffect(() => { - (async () => { - setIsFetching(true); - let data: any = {}; - if (isRelated) { - data = await transformPropFunc(imageData[selectIndex]); - } else { - data = await transformPropFunc(dataSource[selectIndex]); - } - setAttributeList(get(data, 'attributeList', [])); - //防背推 - if (selectIndex === latestSelectIndex.current) { - setSelectItem(data); - setIsFetching(false); - } - })(); - }, [selectIndex, dataSource, imageData, isRelated]); - - const selectqualityScore = useMemo(() => { - return get(selectItem, 'qualityScore'); - }, [selectItem]); - //支持视频url异步获取 - const [flvUrl, setFlvUrl] = useState(null); - const [maxDuration, setMaxDuration] = useState(null); - useEffect(() => { - (async () => { - if (model === 'IMAGE') { - setFlvUrl(null); - setMaxDuration(null); - return; - } - - if (isFunction(transformVideoPropFunc)) { - //先情空 - setFlvUrl(null); - setMaxDuration(null); - const { flvUrl, maxDuration } = await transformVideoPropFunc(selectItem); - //防背推 - if (selectIndex === latestSelectIndex.current) { - setMaxDuration(maxDuration); - setFlvUrl(flvUrl); - } - } else { - setFlvUrl(get(selectItem, 'flvUrl')); - setMaxDuration(get(selectItem, 'maxDuration')); - } - })(); - }, [selectItem, model]); - - //切换选中index时候变更key 让组件走销毁逻辑 减少大图/视频组件内部逻辑复杂度 - const key = 0 - const imgCmpKey = useMemo(() => `img-key-${key}`, [key]); - const videoCmpKey = useMemo(() => `video-key-${key}`, [key]); - - // ========================== 分离参数 ========================= - const CompareViewProp = { - targertImg: generateImg(get(selectItem, 'imgSummary', '')), // 对比图 - score: get(selectItem, 'score'), - similarScore: get(selectItem, 'similarScore'), - sourceImg: - get(selectItem, 'constractKey', '') || - get(selectItem, 'compaterImages.0') || - generateImg(get(selectItem, 'imgSummary', '')), - compaterImages: get(selectItem, 'compaterImages', []), - specialTitle, - isRelated, - }; - const carouselProp = { - selectIndex, - setSelectIndex: setSelectIndexWrapper, - hasPre, - hasNext, - dataSource: carouseDataSource, - ...otherCarouselProp, - } as CarouselProps; - const imgViewProp = { - ...pick(selectItem, ['imageKey', 'odRect', 'attachImg', 'score']), - screenshotButtonRender, - ...otherImgViewProp, - showCrop$, - scale$, - } as ImgViewProps; - - const videoViewProp = { - flvUrl, - maxDuration, - screenshotButtonRender, - ...otherVideoViewProp, - showCrop$, - } as VideoViewProps; - - const ToolProps = { - ...otherToolProp, - isGray: true, - } as ToolProps; - - // ========================== 插槽参数 ========================= - const imgViewRef = useRef(null); - const VideoViewRef = useRef(null); - scale$; - const param: ParamProps = { - tab, - selectItem, - imgViewRef, - VideoViewRef, - model, - setModel, - showCrop$, - scale$, - }; - const slots = getSolt(children, param); - - // ========================== 监听键盘 ========================= - useEffect(() => { - const onKeyDown = (event) => { - const { keyCode } = event; - if (keyCode === KeyCode.LEFT) { - setSelectIndexWrapper((pre) => --pre); - } - if (keyCode === KeyCode.RIGHT) { - setSelectIndexWrapper((pre) => ++pre); - } - }; - document.addEventListener('keydown', onKeyDown); - return () => { - document.removeEventListener('keydownm', onKeyDown); - }; - }, []); - - // ========================== 监听滚轮 ========================= - React.useEffect(() => { - const mousewheelListener = (e) => { - e.preventDefault(); - let direction = 0; - if (e.wheelDelta) { - //IE/Opera/Chrome - if (e.wheelDelta > 0) { - //向上滚动事件 - direction = 1; - } else { - //向下滚动事件 - direction = -1; - } - } else if (e.detail) { - //Firefox - if (e.detail < 0) { - //向上滚动事件 - direction = 1; - } else { - //向下滚动事件 - direction = -1; - } - } - setSelectIndexWrapper((pre) => { - return direction < 0 ? pre + 1 : pre - 1; - }); - }; - let handleMouseWheel; - if (store.bigImgScrollEmit) { - handleMouseWheel = addEventListenerWrap(document, 'mousewheel', mousewheelListener); - } else { - handleMouseWheel?.remove(); - } - return () => { - handleMouseWheel?.remove(); - }; - }, [store.bigImgScrollEmit]); - - const tabList = [ - { - key: 'related', - label: '关联的目标', - children: ( -
    - {showCarousel && ( -
    - -
    - )} -
    { - if (isEmpty(relatedList)) { - e.stopPropagation(); - } else { - try { - const { archiveId, passerbyId } = selectItem; - if (archiveId && passerbyId) { - doubleClick({ - title: '确认取消关联,取消后可在“其他相似目标推荐”处再次关联', - checkboxLabel: '同时移除档案对应轨迹', - checked: true, - onOk: async () => { - try { - await achieveStore.archive.UnLinkTarget(passerbyId, archiveId); - message.success('目标已成功取消关联!'); - // 更新已关联目标列表 - const { relatedPassersby } = await achieveStore.archive.GetRelatedArchive( - archiveId - ); - setRelatedList(relatedPassersby); - setImageData(relatedPassersby); - // 更新当前相似目标列表 - const { similarPassersby } = - await achieveStore.archive.GetSimilarPasserbyList(archiveId); - setSimilarList(similarPassersby); - setSelectIndex((pre) => { - if (pre > 0) { - return pre - 1; - } else { - return 0; - } - }); - } catch (e) { - message.success('目标取消关联失败!'); - console.error(e); - } - }, - }); - } - } catch (e) { - console.error(e); - } - } - }} - > - - 取消关联 -
    -
    - ), - }, - { - key: 'unRlated', - label: '其他相似目标推荐', - children: ( -
    - {showCarousel && ( -
    - -
    - )} - -
    { - if (isEmpty(lastSimData.current)) { - e.stopPropagation(); - } else { - try { - const { archiveId, passerbyId, archiveGroupId, trajectoryId } = selectItem; - - if (archiveId && passerbyId && archiveGroupId && trajectoryId) { - await achieveStore.archive.LinkTarget({ - passerbyId, - archiveId, - archiveGroupId, - trajectoryId, - }); - message.success('目标已成功关联!'); - // 更新当前相似目标列表 - const { similarPassersby } = await achieveStore.archive.GetSimilarPasserbyList( - archiveId - ); - setSimilarList(similarPassersby); - setImageData(similarPassersby); - - // 更新已关联目标列表 - const { relatedPassersby } = await achieveStore.archive.GetRelatedArchive( - archiveId - ); - setRelatedList(relatedPassersby); - setSelectIndex((pre) => { - if (pre > 0) { - return pre - 1; - } else { - return 0; - } - }); - } - } catch (e) { - message.error('目标关联失败!'); - console.error(e); - } - } - }} - > - - 关联 -
    -
    - ), - }, - ]; - return ( - - {!isEmpty(attributeList) && } - {showHeader && ( -
    - )} -
    - {tab !== 'TRACK' && ( - <> - {/* ---------------------------------- 对比图模式 --------------------------------- */} - {model == 'IMAGE' && tab === 'COMPATER' && !isEmpty(selectItem) && ( - - )} - {/* ---------------------------------- 场景图模式 --------------------------------- */} - {!isLoading && - model == 'IMAGE' && - tab === 'NORMAL' && - !isEmpty(selectItem?.rectList) && ( - - )} - {/* -------------------------------- 暂无图片数据 -------------------------------- */} - {!isLoading && model == 'IMAGE' && isEmpty(selectItem) && tab === 'COMPATER' && ( - - )} - {!isLoading && model == 'IMAGE' && isEmpty(selectItem.rectList) && tab === 'NORMAL' && ( - - )} - {/* --------------------------------- 视频播放模式 --------------------------------- */} - {!isLoading && model == 'VIDEO' && ( - - )} - {/* ----------------------------------- 左导航 ---------------------------------- */} - { - if (useVirtual && selectIndex === 0) { - !!loadPre && loadPre(); - //都跳转到第一个 - setSelectIndexWrapper(0); - } else { - setSelectIndexWrapper((pre) => pre - 1); - } - }} - /> - {/* ----------------------------------- 右导航 ---------------------------------- */} - { - if (isRelated) { - if (useVirtual && selectIndex === imageData.length - 1) { - !!loadNext && (await loadNext()); - //都跳转到第一个 - setSelectIndexWrapper(0); - } else { - setSelectIndexWrapper((pre) => pre + 1); - } - } else { - if (useVirtual && selectIndex === dataSource.length - 1) { - !!loadNext && (await loadNext()); - //都跳转到第一个 - setSelectIndexWrapper(0); - } else { - setSelectIndexWrapper((pre) => pre + 1); - } - } - }} - /> - - )} -
    - {/* 工具集合 */} - {tab !== 'TRACK' && showTool && ( - <> -
    - -
    - {slots['after-tool']} - - )} - {/* 人脸质量分 */} - {!!selectqualityScore && store.user.isfaceScore && model == 'IMAGE' && tab === 'NORMAL' && ( -
    {`人脸质量分:${(selectqualityScore as number).toFixed(2)}`}
    - )} - {/* --------------------------------- 模型碰撞组件 --------------------------------- */} - {isRelated && tab !== 'TRACK' && ( -
    - { - setActiveKey(key); - }} - items={tabList.map((item) => { - return { - label: item.label, - key: item.key, - children: item.children, - }; - })} - /> -
    - )} - - ); -}; - -export default observer(BigImageDialog); diff --git a/packages/biz/src/BigImageModal/index.tsx b/packages/biz/src/BigImageModal/index.tsx index 28ae31c..8ee12d5 100644 --- a/packages/biz/src/BigImageModal/index.tsx +++ b/packages/biz/src/BigImageModal/index.tsx @@ -1,162 +1,5 @@ -// @ts-nocheck -import React, { useRef, useState } from 'react' -import { Descriptions, Modal, Tabs } from 'antd'; -import classNames from 'classnames' -import type { ModalProps, DescriptionsProps, TabsProps } from 'antd' -import { get } from '@zhst/func'; -import './index.less' -import Navigation from './components/navigation'; +import BigImageModal from "./BigImageModal"; -const DescriptionsItem = Descriptions.Item - -export const componentPrefix = 'zhst-image' - -export interface BigImageModalProps extends ModalProps { - visible: boolean // 弹框显示隐藏 - descriptionConfig: { - data: { // 描述列表 - title: string; // 标题 - children: Pick // 描述项 - }[] - } - tabsConfig: { // 导航栏配置 - data: Pick & { - key: 'NORMAL' | 'COMPATER' | 'TRACK' - } // 导航栏列表 - } - dataSource: any - imageData: any - relatedData: any -} - -const initialStyle ={ - fontSize: '12px' -} - -const BigImageModal: React.FC = (props) => { - const { - title = '-', - open, - visible, - children, - descriptionConfig = { - data: [] - }, - tabsConfig = { - data: [ - { - label: '对比图模式', - key: '1', - children: '对比图组件', - }, - { - label: '场景图模式', - key: '2', - children: '场景图组件', - } - ], - }, - dataSource = [], - imageData = [], - relatedData = [], - } = props - - const showCropRef = useRef(false); - const scaleRef = useRef(0); - - // ========================== 头切换 ========================= - const [activeKey, setActiveKey] = useState(get(tabsConfig, 'data[0].key')); - - // ========================= 预览切换下标 ========================= - const [previewIndex, setPreviewIndex] = useState(0) - const [isRelated, setIsRelated] = useState(false) - - return ( - - {descriptionConfig.data.map(descriptions => ( - - {descriptions.title} -

    - } - column={8} - style={{ padding: '0 64px' }} - > - {descriptions?.children?.map(item => ( - {item.children} - ))} -
    - ))} - -
    - { - activeKey !== 'TRACK' && ( - <> - {/* ----------------------------------- 上一张按钮 ---------------------------------- */} - 1) : (dataSource.length > 1)} - disabled={previewIndex <= 0} - prev - onClick={() => { - setPreviewIndex((pre) => pre - 1); - }} - /> - {/* ----------------------------------- 下一张按钮 ---------------------------------- */} - = imageData.length - 1) || (previewIndex >= dataSource.length - 1)) && `${componentPrefix}-view-container__nav--disabled`, - `${componentPrefix}-view-container__nav--right` - )} - show={isRelated ? (imageData.length > 1) : (dataSource.length > 1)} - disabled={((previewIndex >= imageData.length - 1) || (previewIndex >= dataSource.length - 1))} - next - onClick={async (e) => { - setPreviewIndex((pre) => pre + 1); - }} - /> - - ) - } -
    -
    - ) -} +export type { BigImageModalProps } from './BigImageModal' export default BigImageModal diff --git a/packages/biz/src/hooks/useTaskState/index.ts b/packages/biz/src/hooks/useTaskState/index.ts deleted file mode 100644 index 0f11dee..0000000 --- a/packages/biz/src/hooks/useTaskState/index.ts +++ /dev/null @@ -1,103 +0,0 @@ -import doRequest from '../../utils/request'; -import { NetworkType, useStores } from '@store/index'; -import { useMount, useUnmount } from '@zhst/hooks'; -import { useRef, useState } from 'react'; -import type { CamerasStatusList, StatusList } from '../../interface' - -const Streams = [ - 'TASK_OVERVIEW_WAIT_START_STREAM', - 'TASK_OVERVIEW_WAIT_STREAM', - 'TASK_OVERVIEW_WAIT_START_SVINFER', -]; - -const StreamsNum = [1, 2, 3]; -const RunsNum = [5, 9]; -const ErrorsNum = [7]; - -const Runs = ['TASK_OVERVIEW_RUNNING', 'TASK_OVERVIEW_FINISH']; - -const Errors = ['TASK_OVERVIEW_ERROR']; - -export const getListTaskStatus = async (data?: { taskIndex: { deviceId: string }[] }) => { - const res = await doRequest<{ - taskStatus: StatusList; - }>({ - url: '/singer.TaskManagerService/ListTaskStatusResponse', - method: 'POST', - data: data || {} - }); - return res; -}; -export const getCameraStatusFunc = (list: StatusList, useNum = false) => { - const _Runs: any = useNum ? RunsNum : Runs; - const _Errors: any = useNum ? ErrorsNum : Errors; - const _Streams: any = useNum ? StreamsNum : Streams; - const res = list.reduce((res, cur) => { - const cameraId = cur.taskIndex.deviceId; - const status = cur.taskOverview; - res.some((ids, i) => { - if (ids.includes(cameraId)) { - res[i] = ids.filter((id) => id !== cameraId); - return true; - } - return false; - }); - if (_Runs.includes(status)) { - res[0].push(cameraId); - } else if (_Errors.includes(status)) { - res[1].push(cameraId); - } else if (_Streams.includes(status)) { - res[2].push(cameraId); - } - return res; - }, [[], [], []]); - return [...res]; -}; -let camerasStatusStoreList: CamerasStatusList = [[], [], []]; -let num = 0; -const useTaskState = () => { - const { store } = useStores(); - const [camerasStatusList, setCamerasStatusList] = - useState(camerasStatusStoreList); - const timerRef = useRef(null); - - const getCameraStatus = (list: StatusList, useNum = false) => { - const res = getCameraStatusFunc(list, useNum); - setCamerasStatusList(res); - }; - const request = (data: { taskStatus: StatusList }[]) => { - if (data) { - const list: StatusList = []; - data.forEach((v) => { - list.push(...v.taskStatus); - }); - getCameraStatus(list, store.networkType === NetworkType.NORMAL); - } - }; - useMount(async () => { - num++; - if (num - 1 > 0) { - return; - } - const res = await getListTaskStatus(); - getCameraStatus(res.taskStatus); - if (store.networkType === NetworkType.DUAL_NETWORK) { - timerRef.current = setInterval(async () => { - const res = await getListTaskStatus(); - request([res]); - }, 2000); - } - }); - useUnmount(() => { - clearInterval(timerRef.current); - setCamerasStatusList([[], [], []]); - num--; - if (num === 0) { - camerasStatusStoreList = [[], [], []]; - } - }); - - return camerasStatusList; -}; - -export default useTaskState; diff --git a/packages/biz/src/utils/constants.ts b/packages/biz/src/utils/constants.ts index a4836c1..465736f 100644 --- a/packages/biz/src/utils/constants.ts +++ b/packages/biz/src/utils/constants.ts @@ -1,7 +1,6 @@ export const OBJECT_GRNER_THRESHOLD = 0.8; //目标图判断性别阈值 export const OBJECT_AGE_TYPE_THRESHOLD = 0.5; //目标图判断年龄段阈值 export const MODE_KEY = 'test_mode'; -export const ROUTER_SHOULD_FILTER = isDev; //是否根据后台配置路由,开发环境全打开 //业务约定 export const SEARCH_IMG_COUNT = 10; //检索图片的最大个数 export const GLOBAL_IS_ITEM_NUMBER_SHOW = false; //是否展示索引 diff --git a/packages/biz/src/utils/request.ts b/packages/biz/src/utils/request.ts deleted file mode 100644 index 2681359..0000000 --- a/packages/biz/src/utils/request.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { extend } from 'umi-request'; -import type { RequestOptionsInit } from 'umi-request'; -import { get } from '@zhst/func'; -import { message } from 'antd'; -import base64 from 'base-64'; - -export class ResponseError extends Error { - name; - data; - response; - request; - type; - constructor( - response: Response, - text: string, - data: D, - request: { - url: string; - options: RequestOptionsInit; - }, - type = 'ResponseError' - ) { - super(text || response.statusText); - this.name = 'ResponseError'; - this.data = data; - this.response = response; - this.request = request; - this.type = type; - } -} - -export const request = extend({ - getResponse: true, - // timeout: 1000, - parseResponse: false, -}); - -//错误处理中间件 -request.use(async (ctx, next) => { - const { req } = ctx; - const { toast = true } = req?.options || {}; - try { - await next(); - const { res } = ctx; - const d = await res.text(); - if (res.status === 401) { - message.warning('登录过期,请重新登录!'); - return; - } - const isEmptyRes = d === ''; //有些后端接口成功会返回空 做下兼容 - const body = !isEmptyRes ? JSON.parse(d) : d; - if (res.status >= 200 && res.status < 300) { - ctx.res = body; - } else { - // 先判断Grpc-Metadata-Errorx-Message - let errMsg = res.headers.get('Grpc-Metadata-Errorx-Message'); - if (errMsg) { - errMsg = window.utf8?.decode(base64.decode(errMsg)); - // 后判断 body中的message - } else if (!errMsg && get(body, 'message')) { - errMsg = `${get(body, 'message')}`; - } else { - // 最后看状态码 - errMsg = '您的网络发生异常,无法连接服务器'; - } - toast && message.error(errMsg); - throw new ResponseError(res, errMsg, d, req, 'CustomError'); - } - } catch (error) { - if (get(error, 'type') !== 'CustomError') { - toast && message.error('您的网络发生异常,无法连接服务器'); - } - throw error; - } -}); - -export default request diff --git a/packages/constants/CHANGELOG.md b/packages/constants/CHANGELOG.md index 444b4f0..4f2555a 100644 --- a/packages/constants/CHANGELOG.md +++ b/packages/constants/CHANGELOG.md @@ -1,5 +1,11 @@ # @zhst/biz +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + ## 0.2.4 ### Patch Changes diff --git a/packages/constants/package.json b/packages/constants/package.json index 423601e..b639d51 100644 --- a/packages/constants/package.json +++ b/packages/constants/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/constants", - "version": "0.2.4", + "version": "0.3.0", "description": "常量库", "keywords": [ "constants", @@ -33,6 +33,5 @@ "access": "public", "registry": "http://10.0.0.77:4874" }, - "dependencies": { - } + "dependencies": {} } diff --git a/packages/constants/src/index.tsx b/packages/constants/src/index.tsx index ac0e8bf..6aa4e57 100644 --- a/packages/constants/src/index.tsx +++ b/packages/constants/src/index.tsx @@ -1,2 +1,3 @@ export * from './camera' export * from './base' +export * from './user' diff --git a/packages/constants/src/user/index.ts b/packages/constants/src/user/index.ts index e69de29..b1c6ea4 100644 --- a/packages/constants/src/user/index.ts +++ b/packages/constants/src/user/index.ts @@ -0,0 +1 @@ +export default {} diff --git a/packages/func/CHANGELOG.md b/packages/func/CHANGELOG.md index 19b1dcf..be9f906 100644 --- a/packages/func/CHANGELOG.md +++ b/packages/func/CHANGELOG.md @@ -1,5 +1,16 @@ # @zhst/utils +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + +### Patch Changes + +- Updated dependencies + - @zhst/request@0.3.0 + ## 0.2.4 ### Patch Changes diff --git a/packages/func/es/camera/constants.d.ts b/packages/func/es/camera/constants.d.ts new file mode 100644 index 0000000..0658bd8 --- /dev/null +++ b/packages/func/es/camera/constants.d.ts @@ -0,0 +1,41 @@ +/** + * 设备类型枚举 + */ +export declare const DeviceType: { + VMS: string; + DIR: string; + CAMERA: string; +}; +export declare const LOCAL_KEY = "local"; +export declare const DIRE_CONNECT_KEY = "direconnect"; +export declare const BOX_LIST_KEY = "boxlist"; +export declare enum VmsplatformOpt { + VMSPLATFORMOPT_ID = 0, + VMSPLATFORMOPT_PLATFORMNAME = 1, + VMSPLATFORMOPT_PLUGINNAME = 2, + VMSPLATFORMOPT_IP = 3, + VMSPLATFORMOPT_PORT = 4, + VMSPLATFORMOPT_USERNAME = 5, + VMSPLATFORMOPT_PASSWORD = 6 +} +export declare enum OPT { + OR = 0, + AND = 1, + ORNOT = 2, + ANDNOT = 3 +} +export declare enum DevicemanagerCameraType { + DEVICEMANAGER_CAMERA_TYPE_DEFAULT = 0, + DEVICEMANAGER_CAMERA_TYPE_NORMAL = 1, + DEVICEMANAGER_CAMERA_TYPE_1400 = 97, + DEVICEMANAGER_CAMERA_TYPE_DHGRABBER = 98, + DEVICEMANAGER_CAMERA_TYPE_HKGRABBER = 99, + DEVICEMANAGER_CAMERA_TYPE_LOCAL = 100 +} +export declare const BOX_DIRECONNECT_PLATFORM_FILTER: { + filtervmsplatformList: { + opt: OPT; + vmsplatformOpt: VmsplatformOpt; + value: string; + }[]; +}; diff --git a/packages/func/es/camera/index.d.ts b/packages/func/es/camera/index.d.ts new file mode 100644 index 0000000..c47dcdd --- /dev/null +++ b/packages/func/es/camera/index.d.ts @@ -0,0 +1,40 @@ +import { DevicemanagerCameraType } from './constants'; +export declare const isFaceCamera: (type: DevicemanagerCameraType) => boolean; +/** + * + * @param value 传入的数据 可以是 item(camera/vms/dirs)/ deviceID + * @param isId + */ +export declare function getDeviceType(value: { + [x: string]: any; + id: any; +} | string): any; +/** + * 后端设备id/vmsid/dirid是三张表 合并在一起不保证唯一 前端生成唯一key + * @param id 设备id + * @param type 设备类型 + */ +export declare function deviceIDToDeviceKey(id: any, type: string, vmsId?: any): string; +/** + * 后端设备id/vmsid/dirid是三张表 合并在一起不保证唯一 前端生成唯一key + * @param item camera/vms/dirs + */ +export declare function deviceToDeviceKey(item: { + [x: string]: any; + id: any; +}): string; +/** + * 设备树key 转 后端设备原始id dirid是string/vms&camera 是number 和后端保持一致 + * @param deviceKey 设备树的id + */ +export declare function deviceKeyToDeviceId(deviceKey: { + split: (arg0: string) => [any, any]; +}): any; +export declare const getVmsIdByDeviceId: (key: string) => string; +/** + * 通过设备id或设备key在树里面找摄像头 + * @param ids cameraId + * @param deviceTree 树 + * @param type "id" | "key" + */ +export declare const findCamerasByInDeviceTree: (ids: never[] | undefined, deviceTree: any, type?: string) => any[]; diff --git a/packages/func/es/file/index.d.ts b/packages/func/es/file/index.d.ts new file mode 100644 index 0000000..7997a29 --- /dev/null +++ b/packages/func/es/file/index.d.ts @@ -0,0 +1,75 @@ +import { Rect } from '@zhst/types'; +/** + * + * @param url 需要转为图片的链接 + * @returns 图片的 dom + */ +export declare const urlToImg: (url: string) => Promise; +export declare const base64DecodeImageKey: (base64ImgKey: string) => string; +/** + * 通过url获取图片的base64字符串 + * @param src 图片链接 + * @param outputFormat 图片格式 + * @returns base64 @string + */ +export declare const getBase64ByUrl: (src: string | URL, outputFormat?: string) => Promise; +/** + * 把文件转base64 + * @param file @file 文件 + * @returns @string + */ +export declare const fileToBase64: (file: any) => Promise; +/** + * + * @param image @file 图片文件 + * @param width @number 宽度 + * @param height @number 高度 + * @returns @string base64 + */ +export declare const getBase64Image: (image: any, width?: any, height?: any) => string; +/** + * 通过图片获取base64 + * @param src 图片地址 + * @returns @string + */ +export declare const getBase64ByImage: (src: string) => Promise; +/** + * url转base64 + * @param {String} url - url地址 + */ +export declare const urlToBase64V2: (url: string) => Promise; +/** + * base64转Blob + * @param {String} base64 - base64 + */ +export declare function base64toBlob(base64: string): Blob | undefined; +/** + * 图片集打包压缩下载 + * 1. url -> base64 -> blob + * 2. 将blob加入jsZip文件夹内,用file-saver保存 + * @param {Array<{url:string,name:string}>} imgDataList + * @param {string} zipName + */ +export declare const downloadPackageImages: (imgDataList: string | any[], zipName: string) => Promise; +export declare function getFileSize(size: number): string; +export declare const dataURLToBlob: (dataurl: string) => Blob; +/** + * key 转 http 链接 + * @param originImgkey 图片的值 ,可以是 base64 也可以是 http链接 + * @param host 图片的域值 + * @returns {string} + */ +export declare const generateImg: (imgKey: string, host?: string) => string; +/** + * 获取指定字符串后面的部分 + * @param imageKey v1_开头的字符串 + * @returns + */ +export declare const getImageKey: (imageKey: string, preFix?: string) => string; +/** + * 获取图片 + * @param img 图片的url链接 + * @param odRect + * @returns file + */ +export declare const getFileByRect: (img: string, odRect: Rect) => Promise; diff --git a/packages/func/es/file/index.js b/packages/func/es/file/index.js index e495fba..1fd9c37 100644 --- a/packages/func/es/file/index.js +++ b/packages/func/es/file/index.js @@ -12,8 +12,7 @@ import Base64 from 'base-64'; import JSZip from 'jszip'; import FileSaver from 'file-saver'; import { matchS3Prefix } from "../utils"; -import { get } from 'lodash-es'; - +import { get, isString } from 'lodash-es'; /** * * @param url 需要转为图片的链接 @@ -323,9 +322,10 @@ export var generateImg = function generateImg(_imgKey) { var imgUrl = ''; //判空 if (!imgKey) return ''; - if (/^(http:|https:)/.test(imgKey)) { + if (/(http|https):\/\/([\w.]+\/?)\S*/ig.test(imgKey)) { return imgKey; } + console.log('imgKey', imgKey); try { if (matchS3Prefix(imgKey)) { imgKey = base64DecodeImageKey(imgKey); @@ -357,4 +357,57 @@ export var getImageKey = function getImageKey(imageKey, preFix) { } else { return imageKey; } -}; \ No newline at end of file +}; + +/** + * 获取图片 + * @param img 图片的url链接 + * @param odRect + * @returns file + */ +export var getFileByRect = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(img, odRect) { + var _commonCanvas$parentN; + var image, url, commonCanvas, commonCtx, base64, blobData, file; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!isString(img)) { + _context2.next = 7; + break; + } + url = generateImg(img); + _context2.next = 4; + return urlToImg(url); + case 4: + image = _context2.sent; + _context2.next = 8; + break; + case 7: + image = img; + case 8: + commonCanvas = document.createElement('canvas'); + commonCanvas.width = odRect.w * image.width; + commonCanvas.height = odRect.h * image.height; + commonCanvas.style.display = 'none'; + document.body.appendChild(commonCanvas); + commonCtx = commonCanvas.getContext('2d'); + commonCtx === null || commonCtx === void 0 || commonCtx.translate(-odRect.x * image.width, -odRect.y * image.height); + commonCtx === null || commonCtx === void 0 || commonCtx.drawImage(image, 0, 0); + base64 = commonCanvas.toDataURL('image/jpeg'); + blobData = dataURLToBlob(base64); + (_commonCanvas$parentN = commonCanvas.parentNode) === null || _commonCanvas$parentN === void 0 || _commonCanvas$parentN.removeChild(commonCanvas); + file = new window.File([blobData], "".concat(new Date().getTime()), { + type: 'image/jpeg' + }); + return _context2.abrupt("return", file); + case 21: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function getFileByRect(_x3, _x4) { + return _ref2.apply(this, arguments); + }; +}(); \ No newline at end of file diff --git a/packages/func/es/index.d.ts b/packages/func/es/index.d.ts new file mode 100644 index 0000000..c7f2505 --- /dev/null +++ b/packages/func/es/index.d.ts @@ -0,0 +1,11 @@ +export * from 'lodash-es'; +export * from './file'; +export * from './map'; +export * from './performance'; +export * from './string'; +export * from './number'; +export * from './time'; +export * from './utils'; +export * from './camera'; +export * from './math'; +export * from './upload'; diff --git a/packages/func/es/index.js b/packages/func/es/index.js index 598dbef..614979f 100644 --- a/packages/func/es/index.js +++ b/packages/func/es/index.js @@ -7,4 +7,5 @@ export * from "./number"; export * from "./time"; export * from "./utils"; export * from "./camera"; -export * from "./math"; \ No newline at end of file +export * from "./math"; +export * from "./upload"; \ No newline at end of file diff --git a/packages/func/es/map/index.d.ts b/packages/func/es/map/index.d.ts new file mode 100644 index 0000000..08fa4a2 --- /dev/null +++ b/packages/func/es/map/index.d.ts @@ -0,0 +1,10 @@ +/** + * 获取经纬信息 + * @param lngLat 位置信息 + * @returns @object { long, lat } + */ +export declare const fixedLngLat: (lngLat?: string) => string; +export declare const transformLngLat: (lngLat?: string) => { + longitude: number; + latitude: number; +} | null; diff --git a/packages/func/es/math/index.d.ts b/packages/func/es/math/index.d.ts new file mode 100644 index 0000000..1ea0b01 --- /dev/null +++ b/packages/func/es/math/index.d.ts @@ -0,0 +1,70 @@ +import { IOdRectOrigin, Rect } from '@zhst/types'; +export declare const ALGORITHM_VERSION: { + 7: string; + 4: string; + 6: string; +}; +export declare const algorithmVersions: string[]; +export declare const getBikeExtendRect: (rect: Rect, maxW: number) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getOtherExtendRect: (srcRect: Rect, maxW: number, maxH: number, type: string) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getNormalization: (srcRect: Rect, maxW: number, maxH: number) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getExtendRect: (normalizationRect: Rect, imgW: number, imgH: number, type: string) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getTransformRect: (image: { + height: number; + width: number; +}, transform: { + translateX: any; + translateY: any; + scale: any; + rotate: any; +}, rect: Rect) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getRotateImg: (image: HTMLImageElement, rotate: number) => File; +/** + * 格式化工具 + * @param originData + * @returns + */ +export declare const getOdRect: (originData: IOdRectOrigin) => { + x: any; + y: any; + w: any; + h: any; + id: any; + qualityScore: any; + algorithmVersion: string; + featureData: any; + objectRectIndex: number; + objectType: any; + objectId: any; + frameTimestamp: any; + sourceObjectId: any; + extendBox: any; +}[]; +export declare const getOdRectV2: (originData: { + odv2Result: any[]; +}) => any; diff --git a/packages/func/es/math/index.js b/packages/func/es/math/index.js index 16da47f..d9d6d04 100644 --- a/packages/func/es/math/index.js +++ b/packages/func/es/math/index.js @@ -1,8 +1,5 @@ var _ALGORITHM_VERSION; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } @@ -14,8 +11,8 @@ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -import { cloneDeep, get, isNull, isString } from 'lodash-es'; -import { dataURLToBlob, generateImg, urlToImg } from "../file"; +import { cloneDeep, get, isNull } from 'lodash-es'; +import { dataURLToBlob } from "../file"; var proto = { Common: { AlgorithmVersion: { @@ -239,7 +236,7 @@ export var getRotateImg = function getRotateImg(image, rotate) { }; /** - * + * 格式化工具 * @param originData * @returns */ @@ -290,7 +287,6 @@ export var getOdRect = function getOdRect(originData) { //档案库od export var getOdRectV2 = function getOdRectV2(originData) { - // const fileKey = 'v1_' + window.btoa('public_' + imgKey.split('public/')[1]); var resp = originData.odv2Result[0]; var subObjects = []; //形体 var data = get(resp, 'objects', []).filter(function (v) { @@ -359,55 +355,4 @@ export var getOdRectV2 = function getOdRectV2(originData) { } console.log(brr); return brr; -}; - -//获取图片 - -export var getFileByRect = /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(img, odRect) { - var _commonCanvas$parentN2; - var image, url, commonCanvas, commonCtx, base64, blobData, file; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - if (!isString(img)) { - _context.next = 9; - break; - } - url = generateImg(img); - console.log(url, '获取图片'); - _context.next = 5; - return urlToImg(url); - case 5: - image = _context.sent; - console.log(image, '获取的图片'); - _context.next = 10; - break; - case 9: - image = img; - case 10: - commonCanvas = document.createElement('canvas'); - commonCanvas.width = odRect.w * image.width; - commonCanvas.height = odRect.h * image.height; - commonCanvas.style.display = 'none'; - document.body.appendChild(commonCanvas); - commonCtx = commonCanvas.getContext('2d'); - commonCtx === null || commonCtx === void 0 || commonCtx.translate(-odRect.x * image.width, -odRect.y * image.height); - commonCtx === null || commonCtx === void 0 || commonCtx.drawImage(image, 0, 0); - base64 = commonCanvas.toDataURL('image/jpeg'); - blobData = dataURLToBlob(base64); - commonCanvas === null || commonCanvas === void 0 || (_commonCanvas$parentN2 = commonCanvas.parentNode) === null || _commonCanvas$parentN2 === void 0 || _commonCanvas$parentN2.removeChild(commonCanvas); - file = new window.File([blobData], "".concat(new Date().getTime()), { - type: 'image/jpeg' - }); - return _context.abrupt("return", file); - case 23: - case "end": - return _context.stop(); - } - }, _callee); - })); - return function getFileByRect(_x, _x2) { - return _ref3.apply(this, arguments); - }; -}(); \ No newline at end of file +}; \ No newline at end of file diff --git a/packages/func/es/number/index.d.ts b/packages/func/es/number/index.d.ts new file mode 100644 index 0000000..b8e65be --- /dev/null +++ b/packages/func/es/number/index.d.ts @@ -0,0 +1,14 @@ +/** + * 设置数据的精度 + * @param originNumber + * @param accuracy 精度 以原点为中心向左为正,向右为负, + * @param isCeil 是否为向上取整 + * @returns number + */ +export declare const setNumberAccuracy: (originNumber: number, accuracy?: number, isCeil?: boolean) => number; +/** + * 获取数字 + * @param number 需要校验的数值 + * @returns @number + */ +export declare const toRealNumber: (number: any) => any; diff --git a/packages/func/es/number/index.js b/packages/func/es/number/index.js index 784dc8d..2d44a2a 100644 --- a/packages/func/es/number/index.js +++ b/packages/func/es/number/index.js @@ -24,4 +24,15 @@ export var setNumberAccuracy = function setNumberAccuracy(originNumber) { returnData = Number(returnData.toFixed(0)); } return returnData; +}; + +/** + * 获取数字 + * @param number 需要校验的数值 + * @returns @number + */ +export var toRealNumber = function toRealNumber(number) { + if (isNaN(number) || number === Infinity) { + return 0; + } else return number; }; \ No newline at end of file diff --git a/packages/func/es/performance/index.d.ts b/packages/func/es/performance/index.d.ts new file mode 100644 index 0000000..22dd838 --- /dev/null +++ b/packages/func/es/performance/index.d.ts @@ -0,0 +1 @@ +export declare const speedConvert: (bps: number, contertUnit?: number) => string; diff --git a/packages/func/es/string/index.d.ts b/packages/func/es/string/index.d.ts new file mode 100644 index 0000000..a209796 --- /dev/null +++ b/packages/func/es/string/index.d.ts @@ -0,0 +1,7 @@ +export declare const getStrLength: (str: string) => number; +/** + * js截取字符串,中英文都能用 + * @param str:需要截取的字符串 + * @param len: 需要截取的长度 + */ +export declare const cutStr: (str: string, len: number) => string | String | undefined; diff --git a/packages/func/es/time/index.d.ts b/packages/func/es/time/index.d.ts new file mode 100644 index 0000000..28b4d03 --- /dev/null +++ b/packages/func/es/time/index.d.ts @@ -0,0 +1,11 @@ +export declare const formateDuration: (diff: number) => string; +export declare function generateTime(): { + startDateTime: number; + endDateTime: number; +}; +/** + * 格式化时间为 00:00 + * @param seconds 时间,单位秒 + * @returns + */ +export declare function formatDurationTime(seconds: number): string; diff --git a/packages/func/es/time/index.js b/packages/func/es/time/index.js index 9feb0a8..b60c8aa 100644 --- a/packages/func/es/time/index.js +++ b/packages/func/es/time/index.js @@ -46,4 +46,15 @@ export function generateTime() { startDateTime: startDateTime, endDateTime: endDateTime }; +} + +/** + * 格式化时间为 00:00 + * @param seconds 时间,单位秒 + * @returns + */ +export function formatDurationTime(seconds) { + var minutes = Math.floor(seconds / 60) || 0; + var remainingSeconds = Math.floor(seconds % 60); + return (minutes < 10 ? "0".concat(minutes) : minutes) + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds; } \ No newline at end of file diff --git a/packages/func/es/upload/index.d.ts b/packages/func/es/upload/index.d.ts new file mode 100644 index 0000000..8c370db --- /dev/null +++ b/packages/func/es/upload/index.d.ts @@ -0,0 +1,8 @@ +type uploadOption = { + bucket?: string; + dir?: string; + withSuFuffix?: boolean; +}; +export declare const commonUpload: (file: File, option: uploadOption | undefined, type: string) => Promise; +export declare const upload: (file: File, option?: uploadOption) => Promise; +export {}; diff --git a/packages/func/es/upload/index.js b/packages/func/es/upload/index.js index 6157f92..e978a53 100644 --- a/packages/func/es/upload/index.js +++ b/packages/func/es/upload/index.js @@ -7,6 +7,7 @@ import { getFileSuffix, getImageSuffixByFileType } from "../utils"; import base64 from "base-64"; import { v4 as uuidV4 } from 'uuid'; import { get } from "lodash-es"; +import request from '@zhst/request'; //小文件上传走s3 var defaultBucket = 'public'; @@ -60,7 +61,7 @@ export var commonUpload = /*#__PURE__*/function () { break; } _context.next = 3; - return doRequest({ + return request({ method: 'PUT', url: '/singer.FileServerService/PutObject', data: { @@ -71,6 +72,7 @@ export var commonUpload = /*#__PURE__*/function () { putObjectOption: { contentType: file.type }, + // @ts-ignore fileDataBase64: (_reader$result = reader.result) === null || _reader$result === void 0 ? void 0 : _reader$result.split(';base64,')[1] } }); diff --git a/packages/func/es/utils/index.d.ts b/packages/func/es/utils/index.d.ts new file mode 100644 index 0000000..4a5e574 --- /dev/null +++ b/packages/func/es/utils/index.d.ts @@ -0,0 +1,36 @@ +export { default as isChrome } from './isChrome'; +export declare const matchS3Prefix: (str: string) => boolean; +/** + * 通过文件名获取文件类型 + * @param fileName 文件名称 + * @returns 文件类型 + */ +export declare const getFileSuffix: (fileName: string) => string; +/** + * 通过类型获取文件名 + * @param type 类型 + * @returns + */ +export declare const getImageSuffixByFileType: (type: string) => string; +export declare function getChromeVersion(): number | false; +export declare const nextTick: (func: (value: void) => void | PromiseLike) => void; +export declare const loop: (items: string | any[], callback: (arg0: any) => any) => void; +export declare const addEventListenerWrapper: (target: any, eventType: string, cb: any, option?: any) => { + remove: () => void; +}; +/** + * Get transforms base on the given object. + * @param {Object} obj - The target object. + * @returns {string} A string contains transform values. + */ +export declare function getTransforms({ rotate, scaleX, scaleY, translateX, translateY, }: { + rotate?: number; + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; +}): { + WebkitTransform: string; + msTransform: string; + transform: string; +}; diff --git a/packages/func/es/utils/index.js b/packages/func/es/utils/index.js index 4316375..a463b52 100644 --- a/packages/func/es/utils/index.js +++ b/packages/func/es/utils/index.js @@ -89,7 +89,7 @@ export var loop = function loop(items, callback) { } } }; -export var addEventListener = function addEventListener(target, eventType, cb, option) { +export var addEventListenerWrapper = function addEventListenerWrapper(target, eventType, cb, option) { /* eslint camelcase: 2 */ var callback = ReactDOM.unstable_batchedUpdates ? function run(e) { ReactDOM.unstable_batchedUpdates(cb, e); diff --git a/packages/func/es/utils/isChrome.d.ts b/packages/func/es/utils/isChrome.d.ts new file mode 100644 index 0000000..2d07ceb --- /dev/null +++ b/packages/func/es/utils/isChrome.d.ts @@ -0,0 +1,3 @@ +export declare const isBrowser: boolean; +declare const isChrome: () => boolean; +export default isChrome; diff --git a/packages/func/es/utils/isChrome.js b/packages/func/es/utils/isChrome.js index 7cfe2e3..6c1ad42 100644 --- a/packages/func/es/utils/isChrome.js +++ b/packages/func/es/utils/isChrome.js @@ -1,7 +1,7 @@ -export var isBrowser = !!(typeof window !== 'undefined' && window); +export var isBrowser = !!(typeof window !== 'undefined' && window.document && window.document.createElement); var isChrome = function isChrome() { var winNav = isBrowser && window.navigator; - var vendorName = winNav && winNav.vendor; + var vendorName = winNav && (winNav === null || winNav === void 0 ? void 0 : winNav.vendor); var userAgent = winNav && winNav.userAgent; //@ts-ignore diff --git a/packages/func/lib/camera/constants.d.ts b/packages/func/lib/camera/constants.d.ts new file mode 100644 index 0000000..0658bd8 --- /dev/null +++ b/packages/func/lib/camera/constants.d.ts @@ -0,0 +1,41 @@ +/** + * 设备类型枚举 + */ +export declare const DeviceType: { + VMS: string; + DIR: string; + CAMERA: string; +}; +export declare const LOCAL_KEY = "local"; +export declare const DIRE_CONNECT_KEY = "direconnect"; +export declare const BOX_LIST_KEY = "boxlist"; +export declare enum VmsplatformOpt { + VMSPLATFORMOPT_ID = 0, + VMSPLATFORMOPT_PLATFORMNAME = 1, + VMSPLATFORMOPT_PLUGINNAME = 2, + VMSPLATFORMOPT_IP = 3, + VMSPLATFORMOPT_PORT = 4, + VMSPLATFORMOPT_USERNAME = 5, + VMSPLATFORMOPT_PASSWORD = 6 +} +export declare enum OPT { + OR = 0, + AND = 1, + ORNOT = 2, + ANDNOT = 3 +} +export declare enum DevicemanagerCameraType { + DEVICEMANAGER_CAMERA_TYPE_DEFAULT = 0, + DEVICEMANAGER_CAMERA_TYPE_NORMAL = 1, + DEVICEMANAGER_CAMERA_TYPE_1400 = 97, + DEVICEMANAGER_CAMERA_TYPE_DHGRABBER = 98, + DEVICEMANAGER_CAMERA_TYPE_HKGRABBER = 99, + DEVICEMANAGER_CAMERA_TYPE_LOCAL = 100 +} +export declare const BOX_DIRECONNECT_PLATFORM_FILTER: { + filtervmsplatformList: { + opt: OPT; + vmsplatformOpt: VmsplatformOpt; + value: string; + }[]; +}; diff --git a/packages/func/lib/camera/constants.js b/packages/func/lib/camera/constants.js new file mode 100644 index 0000000..efd28fa --- /dev/null +++ b/packages/func/lib/camera/constants.js @@ -0,0 +1,90 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/camera/constants.ts +var constants_exports = {}; +__export(constants_exports, { + BOX_DIRECONNECT_PLATFORM_FILTER: () => BOX_DIRECONNECT_PLATFORM_FILTER, + BOX_LIST_KEY: () => BOX_LIST_KEY, + DIRE_CONNECT_KEY: () => DIRE_CONNECT_KEY, + DeviceType: () => DeviceType, + DevicemanagerCameraType: () => DevicemanagerCameraType, + LOCAL_KEY: () => LOCAL_KEY, + OPT: () => OPT, + VmsplatformOpt: () => VmsplatformOpt +}); +module.exports = __toCommonJS(constants_exports); +var DeviceType = { + VMS: "vms", + DIR: "dir", + CAMERA: "camera" +}; +var LOCAL_KEY = "local"; +var DIRE_CONNECT_KEY = "direconnect"; +var BOX_LIST_KEY = "boxlist"; +var VmsplatformOpt = /* @__PURE__ */ ((VmsplatformOpt2) => { + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_ID"] = 0] = "VMSPLATFORMOPT_ID"; + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_PLATFORMNAME"] = 1] = "VMSPLATFORMOPT_PLATFORMNAME"; + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_PLUGINNAME"] = 2] = "VMSPLATFORMOPT_PLUGINNAME"; + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_IP"] = 3] = "VMSPLATFORMOPT_IP"; + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_PORT"] = 4] = "VMSPLATFORMOPT_PORT"; + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_USERNAME"] = 5] = "VMSPLATFORMOPT_USERNAME"; + VmsplatformOpt2[VmsplatformOpt2["VMSPLATFORMOPT_PASSWORD"] = 6] = "VMSPLATFORMOPT_PASSWORD"; + return VmsplatformOpt2; +})(VmsplatformOpt || {}); +var OPT = /* @__PURE__ */ ((OPT2) => { + OPT2[OPT2["OR"] = 0] = "OR"; + OPT2[OPT2["AND"] = 1] = "AND"; + OPT2[OPT2["ORNOT"] = 2] = "ORNOT"; + OPT2[OPT2["ANDNOT"] = 3] = "ANDNOT"; + return OPT2; +})(OPT || {}); +var DevicemanagerCameraType = /* @__PURE__ */ ((DevicemanagerCameraType2) => { + DevicemanagerCameraType2[DevicemanagerCameraType2["DEVICEMANAGER_CAMERA_TYPE_DEFAULT"] = 0] = "DEVICEMANAGER_CAMERA_TYPE_DEFAULT"; + DevicemanagerCameraType2[DevicemanagerCameraType2["DEVICEMANAGER_CAMERA_TYPE_NORMAL"] = 1] = "DEVICEMANAGER_CAMERA_TYPE_NORMAL"; + DevicemanagerCameraType2[DevicemanagerCameraType2["DEVICEMANAGER_CAMERA_TYPE_1400"] = 97] = "DEVICEMANAGER_CAMERA_TYPE_1400"; + DevicemanagerCameraType2[DevicemanagerCameraType2["DEVICEMANAGER_CAMERA_TYPE_DHGRABBER"] = 98] = "DEVICEMANAGER_CAMERA_TYPE_DHGRABBER"; + DevicemanagerCameraType2[DevicemanagerCameraType2["DEVICEMANAGER_CAMERA_TYPE_HKGRABBER"] = 99] = "DEVICEMANAGER_CAMERA_TYPE_HKGRABBER"; + DevicemanagerCameraType2[DevicemanagerCameraType2["DEVICEMANAGER_CAMERA_TYPE_LOCAL"] = 100] = "DEVICEMANAGER_CAMERA_TYPE_LOCAL"; + return DevicemanagerCameraType2; +})(DevicemanagerCameraType || {}); +var BOX_DIRECONNECT_PLATFORM_FILTER = { + filtervmsplatformList: [ + { + opt: 0 /* OR */, + vmsplatformOpt: 1 /* VMSPLATFORMOPT_PLATFORMNAME */, + value: "direconnect" + }, + { + opt: 0 /* OR */, + vmsplatformOpt: 1 /* VMSPLATFORMOPT_PLATFORMNAME */, + value: "boxlist" + } + ] +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BOX_DIRECONNECT_PLATFORM_FILTER, + BOX_LIST_KEY, + DIRE_CONNECT_KEY, + DeviceType, + DevicemanagerCameraType, + LOCAL_KEY, + OPT, + VmsplatformOpt +}); diff --git a/packages/func/lib/camera/index.d.ts b/packages/func/lib/camera/index.d.ts new file mode 100644 index 0000000..c47dcdd --- /dev/null +++ b/packages/func/lib/camera/index.d.ts @@ -0,0 +1,40 @@ +import { DevicemanagerCameraType } from './constants'; +export declare const isFaceCamera: (type: DevicemanagerCameraType) => boolean; +/** + * + * @param value 传入的数据 可以是 item(camera/vms/dirs)/ deviceID + * @param isId + */ +export declare function getDeviceType(value: { + [x: string]: any; + id: any; +} | string): any; +/** + * 后端设备id/vmsid/dirid是三张表 合并在一起不保证唯一 前端生成唯一key + * @param id 设备id + * @param type 设备类型 + */ +export declare function deviceIDToDeviceKey(id: any, type: string, vmsId?: any): string; +/** + * 后端设备id/vmsid/dirid是三张表 合并在一起不保证唯一 前端生成唯一key + * @param item camera/vms/dirs + */ +export declare function deviceToDeviceKey(item: { + [x: string]: any; + id: any; +}): string; +/** + * 设备树key 转 后端设备原始id dirid是string/vms&camera 是number 和后端保持一致 + * @param deviceKey 设备树的id + */ +export declare function deviceKeyToDeviceId(deviceKey: { + split: (arg0: string) => [any, any]; +}): any; +export declare const getVmsIdByDeviceId: (key: string) => string; +/** + * 通过设备id或设备key在树里面找摄像头 + * @param ids cameraId + * @param deviceTree 树 + * @param type "id" | "key" + */ +export declare const findCamerasByInDeviceTree: (ids: never[] | undefined, deviceTree: any, type?: string) => any[]; diff --git a/packages/func/lib/camera/index.js b/packages/func/lib/camera/index.js new file mode 100644 index 0000000..b7ae6f1 --- /dev/null +++ b/packages/func/lib/camera/index.js @@ -0,0 +1,143 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/camera/index.ts +var camera_exports = {}; +__export(camera_exports, { + deviceIDToDeviceKey: () => deviceIDToDeviceKey, + deviceKeyToDeviceId: () => deviceKeyToDeviceId, + deviceToDeviceKey: () => deviceToDeviceKey, + findCamerasByInDeviceTree: () => findCamerasByInDeviceTree, + getDeviceType: () => getDeviceType, + getVmsIdByDeviceId: () => getVmsIdByDeviceId, + isFaceCamera: () => isFaceCamera +}); +module.exports = __toCommonJS(camera_exports); +var import_lodash_es = require("lodash-es"); +var import_utils = require("../utils"); +var import_constants = require("./constants"); +var isFaceCamera = (type) => { + return [ + import_constants.DevicemanagerCameraType.DEVICEMANAGER_CAMERA_TYPE_1400, + import_constants.DevicemanagerCameraType.DEVICEMANAGER_CAMERA_TYPE_HKGRABBER, + import_constants.DevicemanagerCameraType.DEVICEMANAGER_CAMERA_TYPE_DHGRABBER + ].includes(type); +}; +function getDeviceType(value) { + let type; + let isDeviceKey = (0, import_lodash_es.isString)(value); + if (isDeviceKey) { + type = value.split("_")[0]; + } else { + if ((0, import_lodash_es.has)(value, "longitude")) { + type = import_constants.DeviceType["CAMERA"]; + } + if ((0, import_lodash_es.has)(value, "ip")) { + type = import_constants.DeviceType["VMS"]; + } + if (!type) { + type = import_constants.DeviceType["DIR"]; + } + } + return type; +} +function deviceIDToDeviceKey(id, type, vmsId) { + if (type == import_constants.DeviceType["DIR"]) { + return `${type}_${id}_${vmsId}`; + } else { + return `${type}_${id}`; + } +} +function deviceToDeviceKey(item) { + let deviceKey = ""; + let type = getDeviceType(item); + if (!type) { + console.error("device type is null!"); + } + switch (type) { + case import_constants.DeviceType["DIR"]: + { + let dirId = item["dirid"] || item["dirId"]; + if (!dirId && dirId !== 0) { + console.error("dirId type is null!"); + } + let vmsId = (0, import_lodash_es.get)(item, "extendInfo.vmsPlatformId"); + if (!vmsId && vmsId !== 0) { + console.error("vmsId type is null!"); + } + deviceKey = `${type}_${dirId}_${vmsId}`; + } + break; + case import_constants.DeviceType["VMS"]: + deviceKey = `${type}_${item["id"]}`; + break; + case import_constants.DeviceType["CAMERA"]: + { + let vmsId = (0, import_lodash_es.get)(item, "extendInfo.vmsPlatformId"); + if (!vmsId && vmsId !== 0) { + console.error("vmsId type is null!"); + } + deviceKey = `${type}_${item.id}`; + } + break; + } + return deviceKey; +} +function deviceKeyToDeviceId(deviceKey) { + let [type, id] = deviceKey.split("_"); + return type === import_constants.DeviceType["DIR"] ? id : Number(id); +} +var getVmsIdByDeviceId = (key) => { + const type = getDeviceType(key); + let vmsId = ""; + switch (type) { + case import_constants.DeviceType["CAMERA"]: + case import_constants.DeviceType["DIR"]: + vmsId = key.split("_")[2]; + break; + case import_constants.DeviceType["VMS"]: + vmsId = key.split("_")[1]; + break; + } + if (!vmsId) { + console.error("vmsid is null!"); + } + return vmsId; +}; +var findCamerasByInDeviceTree = (ids = [], deviceTree, type = "id") => { + let cameraInfoList = []; + let _ids = ids.map((v) => String(v)); + (0, import_utils.loop)(deviceTree, (item) => { + let isCamera = getDeviceType((0, import_lodash_es.get)(item, "key", "")) === import_constants.DeviceType["CAMERA"]; + let isMatch = type === "key" ? _ids.includes((0, import_lodash_es.get)(item, "key")) : _ids.includes(`${(0, import_lodash_es.get)(item, "origin.id")}`); + if (isCamera && isMatch) { + cameraInfoList.push(item); + } + }); + return cameraInfoList; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + deviceIDToDeviceKey, + deviceKeyToDeviceId, + deviceToDeviceKey, + findCamerasByInDeviceTree, + getDeviceType, + getVmsIdByDeviceId, + isFaceCamera +}); diff --git a/packages/func/lib/file/index.d.ts b/packages/func/lib/file/index.d.ts new file mode 100644 index 0000000..7997a29 --- /dev/null +++ b/packages/func/lib/file/index.d.ts @@ -0,0 +1,75 @@ +import { Rect } from '@zhst/types'; +/** + * + * @param url 需要转为图片的链接 + * @returns 图片的 dom + */ +export declare const urlToImg: (url: string) => Promise; +export declare const base64DecodeImageKey: (base64ImgKey: string) => string; +/** + * 通过url获取图片的base64字符串 + * @param src 图片链接 + * @param outputFormat 图片格式 + * @returns base64 @string + */ +export declare const getBase64ByUrl: (src: string | URL, outputFormat?: string) => Promise; +/** + * 把文件转base64 + * @param file @file 文件 + * @returns @string + */ +export declare const fileToBase64: (file: any) => Promise; +/** + * + * @param image @file 图片文件 + * @param width @number 宽度 + * @param height @number 高度 + * @returns @string base64 + */ +export declare const getBase64Image: (image: any, width?: any, height?: any) => string; +/** + * 通过图片获取base64 + * @param src 图片地址 + * @returns @string + */ +export declare const getBase64ByImage: (src: string) => Promise; +/** + * url转base64 + * @param {String} url - url地址 + */ +export declare const urlToBase64V2: (url: string) => Promise; +/** + * base64转Blob + * @param {String} base64 - base64 + */ +export declare function base64toBlob(base64: string): Blob | undefined; +/** + * 图片集打包压缩下载 + * 1. url -> base64 -> blob + * 2. 将blob加入jsZip文件夹内,用file-saver保存 + * @param {Array<{url:string,name:string}>} imgDataList + * @param {string} zipName + */ +export declare const downloadPackageImages: (imgDataList: string | any[], zipName: string) => Promise; +export declare function getFileSize(size: number): string; +export declare const dataURLToBlob: (dataurl: string) => Blob; +/** + * key 转 http 链接 + * @param originImgkey 图片的值 ,可以是 base64 也可以是 http链接 + * @param host 图片的域值 + * @returns {string} + */ +export declare const generateImg: (imgKey: string, host?: string) => string; +/** + * 获取指定字符串后面的部分 + * @param imageKey v1_开头的字符串 + * @returns + */ +export declare const getImageKey: (imageKey: string, preFix?: string) => string; +/** + * 获取图片 + * @param img 图片的url链接 + * @param odRect + * @returns file + */ +export declare const getFileByRect: (img: string, odRect: Rect) => Promise; diff --git a/packages/func/lib/file/index.js b/packages/func/lib/file/index.js new file mode 100644 index 0000000..5199612 --- /dev/null +++ b/packages/func/lib/file/index.js @@ -0,0 +1,318 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/file/index.ts +var file_exports = {}; +__export(file_exports, { + base64DecodeImageKey: () => base64DecodeImageKey, + base64toBlob: () => base64toBlob, + dataURLToBlob: () => dataURLToBlob, + downloadPackageImages: () => downloadPackageImages, + fileToBase64: () => fileToBase64, + generateImg: () => generateImg, + getBase64ByImage: () => getBase64ByImage, + getBase64ByUrl: () => getBase64ByUrl, + getBase64Image: () => getBase64Image, + getFileByRect: () => getFileByRect, + getFileSize: () => getFileSize, + getImageKey: () => getImageKey, + urlToBase64V2: () => urlToBase64V2, + urlToImg: () => urlToImg +}); +module.exports = __toCommonJS(file_exports); +var import_base_64 = __toESM(require("base-64")); +var import_jszip = __toESM(require("jszip")); +var import_file_saver = __toESM(require("file-saver")); +var import_utils = require("../utils"); +var import_lodash_es = require("lodash-es"); +var urlToImg = (url) => { + const resImage = new Promise((resolve) => { + const image = new Image(); + image.crossOrigin = ""; + image.src = url; + image.onload = () => { + resolve(image); + }; + }); + return resImage; +}; +var base64DecodeImageKey = (base64ImgKey) => { + let tempStr = base64ImgKey; + if ((0, import_utils.matchS3Prefix)(tempStr)) { + tempStr = tempStr.replace(/^v[0-9]_/, ""); + tempStr = import_base_64.default.decode(tempStr); + } + const [bucket, ...pathArr] = tempStr.split("_"); + return tempStr = `${bucket}/${pathArr.join("_")}`; +}; +var getBase64ByUrl = function(src, outputFormat = "image/png") { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open("GET", src, true); + xhr.responseType = "arraybuffer"; + xhr.onload = function(e) { + if (Number(xhr.status) === 200) { + const uInt8Array = new Uint8Array(xhr.response); + let i = uInt8Array.length; + const binaryString = new Array(i); + while (i--) { + binaryString[i] = String.fromCharCode(uInt8Array[i]); + } + const data = binaryString.join(""); + const base64 = window.btoa(data); + const dataUrl = "data:" + (outputFormat || "image/png") + ";base64," + base64; + resolve(dataUrl); + } else { + reject(e); + } + }; + xhr.onerror = (e) => { + reject(e); + }; + xhr.send(); + }); +}; +var fileToBase64 = (file) => { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = function(e) { + resolve(e == null ? void 0 : e.target.result); + }; + reader.onerror = function(e) { + reject(e); + }; + }); +}; +var getBase64Image = (image, width, height) => { + const canvas = document.createElement("canvas"); + canvas.width = width !== void 0 ? width : image.width; + canvas.height = height !== void 0 ? height : image.height; + const ctx = canvas.getContext("2d"); + ctx == null ? void 0 : ctx.drawImage(image, 0, 0, canvas.width, canvas.height); + const ext = image.src.substring(image.src.lastIndexOf(".") + 1).toLowerCase(); + const dataURL = canvas.toDataURL("image/" + ext); + return dataURL; +}; +var getBase64ByImage = function(src) { + return new Promise((resolve, reject) => { + const image = new Image(); + const timestamp = (/* @__PURE__ */ new Date()).getTime(); + const imgUrl = src + "?" + timestamp; + image.src = imgUrl; + image.onload = function() { + function getBase64Image2(img) { + const canvas = document.createElement("canvas"); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext("2d"); + ctx == null ? void 0 : ctx.drawImage(img, 0, 0, img.width, img.height); + const ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); + const dataURL = canvas.toDataURL("image/" + ext); + return dataURL; + } + const base64 = getBase64Image2(image); + resolve(base64); + }; + image.onerror = (e) => { + reject(e); + }; + }); +}; +var urlToBase64V2 = (url) => { + return new Promise((resolve, reject) => { + let image = new Image(); + image.onload = function() { + var _a; + let canvas = document.createElement("canvas"); + canvas.width = image.naturalWidth; + canvas.height = image.naturalHeight; + (_a = canvas == null ? void 0 : canvas.getContext("2d")) == null ? void 0 : _a.drawImage(image, 0, 0); + let result = canvas.toDataURL("image/png"); + resolve(result); + }; + const imgUrl = url; + image.setAttribute("crossOrigin", "Anonymous"); + image.src = imgUrl; + image.onerror = () => { + reject(new Error("Images fail to load")); + }; + }).catch((error) => { + throw new Error(error); + }); +}; +function base64toBlob(base64) { + if (!base64) + return; + var arr = base64.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); + while (n--) { + u8arr[n] = bstr.charCodeAt(n); + } + return new Blob([u8arr], { type: mime }); +} +var downloadPackageImages = async (imgDataList, zipName) => { + let imgDataDownLoadList = []; + let imgBlobList = []; + let imageSuffix = []; + let zip = new import_jszip.default(); + let img = zip.folder(zipName); + try { + for (let i2 = 0; i2 < imgDataList.length; i2++) { + let src = imgDataList[i2].url; + let suffix = src.substring(src.lastIndexOf(".")); + let base64ByUrl = await urlToBase64V2(imgDataList[i2].url); + if (!base64ByUrl) + continue; + let blob = base64toBlob(base64ByUrl); + imgDataDownLoadList.push(imgDataList[i2]); + imgBlobList.push(blob); + imageSuffix.push(suffix); + } + if (imgBlobList.length === 0) + throw new Error("The number of pictures is zero !"); + if (imgBlobList.length > 0) { + for (var i = 0; i < imgBlobList.length; i++) { + img == null ? void 0 : img.file( + imgDataDownLoadList[i].name + (0, import_lodash_es.get)(imageSuffix, `.${i}`, imageSuffix[0]), + // @ts-ignore + imgBlobList[i], + { + base64: true + } + ); + } + } + zip.generateAsync({ type: "blob" }).then(function(content) { + import_file_saver.default.saveAs(content, zipName + ".zip"); + }); + } catch (error) { + throw new Error(error); + } +}; +function getFileSize(size) { + if (!size) + return ""; + var num = 1024; + if (size < num) + return size + "B"; + if (size < Math.pow(num, 2)) + return (size / num).toFixed(2) + "K"; + if (size < Math.pow(num, 3)) + return (size / Math.pow(num, 2)).toFixed(2) + "M"; + if (size < Math.pow(num, 4)) + return (size / Math.pow(num, 3)).toFixed(2) + "G"; + return (size / Math.pow(num, 4)).toFixed(2) + "T"; +} +var dataURLToBlob = (dataurl) => { + const arr = dataurl.split(","); + const mime = arr[0].match(/:(.*?);/)[1]; + const bstr = atob(arr[1]); + let n = bstr.length; + const u8arr = new Uint8Array(n); + while (n--) { + u8arr[n] = bstr.charCodeAt(n); + } + return new Blob([u8arr], { type: mime }); +}; +var generateImg = (_imgKey, host = "http://10.0.0.120") => { + let imgKey = _imgKey; + let imgUrl = ""; + if (!imgKey) + return ""; + if (/(http|https):\/\/([\w.]+\/?)\S*/ig.test(imgKey)) { + return imgKey; + } + console.log("imgKey", imgKey); + try { + if ((0, import_utils.matchS3Prefix)(imgKey)) { + imgKey = base64DecodeImageKey(imgKey); + if (imgKey.endsWith("/")) { + const i = imgKey.substring(0, imgKey.length - 1); + imgKey = i; + } + } + imgUrl = `${host}/file/${imgKey}`; + if (_imgKey.includes("v3")) { + imgUrl = `${host}/minio/${imgKey}`; + } + } catch (error) { + console.error(error); + imgUrl = ""; + } + return imgUrl; +}; +var getImageKey = (imageKey, preFix) => { + const splitIndex = preFix || "v1_"; + if (imageKey.startsWith(splitIndex)) { + return window.atob(imageKey.split(splitIndex)[1]).replace("_", "/"); + } else { + return imageKey; + } +}; +var getFileByRect = async (img, odRect) => { + var _a; + let image; + if ((0, import_lodash_es.isString)(img)) { + const url = generateImg(img); + image = await urlToImg(url); + } else { + image = img; + } + const commonCanvas = document.createElement("canvas"); + commonCanvas.width = odRect.w * image.width; + commonCanvas.height = odRect.h * image.height; + commonCanvas.style.display = "none"; + document.body.appendChild(commonCanvas); + const commonCtx = commonCanvas.getContext("2d"); + commonCtx == null ? void 0 : commonCtx.translate(-odRect.x * image.width, -odRect.y * image.height); + commonCtx == null ? void 0 : commonCtx.drawImage(image, 0, 0); + const base64 = commonCanvas.toDataURL("image/jpeg"); + const blobData = dataURLToBlob(base64); + (_a = commonCanvas.parentNode) == null ? void 0 : _a.removeChild(commonCanvas); + const file = new window.File([blobData], `${(/* @__PURE__ */ new Date()).getTime()}`, { + type: "image/jpeg" + }); + return file; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + base64DecodeImageKey, + base64toBlob, + dataURLToBlob, + downloadPackageImages, + fileToBase64, + generateImg, + getBase64ByImage, + getBase64ByUrl, + getBase64Image, + getFileByRect, + getFileSize, + getImageKey, + urlToBase64V2, + urlToImg +}); diff --git a/packages/func/lib/index.d.ts b/packages/func/lib/index.d.ts new file mode 100644 index 0000000..c7f2505 --- /dev/null +++ b/packages/func/lib/index.d.ts @@ -0,0 +1,11 @@ +export * from 'lodash-es'; +export * from './file'; +export * from './map'; +export * from './performance'; +export * from './string'; +export * from './number'; +export * from './time'; +export * from './utils'; +export * from './camera'; +export * from './math'; +export * from './upload'; diff --git a/packages/func/lib/index.js b/packages/func/lib/index.js new file mode 100644 index 0000000..b25df00 --- /dev/null +++ b/packages/func/lib/index.js @@ -0,0 +1,43 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, require("lodash-es"), module.exports); +__reExport(src_exports, require("./file"), module.exports); +__reExport(src_exports, require("./map"), module.exports); +__reExport(src_exports, require("./performance"), module.exports); +__reExport(src_exports, require("./string"), module.exports); +__reExport(src_exports, require("./number"), module.exports); +__reExport(src_exports, require("./time"), module.exports); +__reExport(src_exports, require("./utils"), module.exports); +__reExport(src_exports, require("./camera"), module.exports); +__reExport(src_exports, require("./math"), module.exports); +__reExport(src_exports, require("./upload"), module.exports); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ...require("lodash-es"), + ...require("./file"), + ...require("./map"), + ...require("./performance"), + ...require("./string"), + ...require("./number"), + ...require("./time"), + ...require("./utils"), + ...require("./camera"), + ...require("./math"), + ...require("./upload") +}); diff --git a/packages/func/lib/map/index.d.ts b/packages/func/lib/map/index.d.ts new file mode 100644 index 0000000..08fa4a2 --- /dev/null +++ b/packages/func/lib/map/index.d.ts @@ -0,0 +1,10 @@ +/** + * 获取经纬信息 + * @param lngLat 位置信息 + * @returns @object { long, lat } + */ +export declare const fixedLngLat: (lngLat?: string) => string; +export declare const transformLngLat: (lngLat?: string) => { + longitude: number; + latitude: number; +} | null; diff --git a/packages/func/lib/map/index.js b/packages/func/lib/map/index.js new file mode 100644 index 0000000..39c614a --- /dev/null +++ b/packages/func/lib/map/index.js @@ -0,0 +1,54 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/map/index.ts +var map_exports = {}; +__export(map_exports, { + fixedLngLat: () => fixedLngLat, + transformLngLat: () => transformLngLat +}); +module.exports = __toCommonJS(map_exports); +var fixedLngLat = (lngLat) => { + if (!lngLat) { + return ""; + } + const lngLatArr = lngLat.split(","); + const longitude = Number(lngLatArr[0]).toFixed(6); + const latitude = Number(lngLatArr[1]).toFixed(6); + if (lngLatArr.length < 2) { + return ""; + } + return `${longitude},${latitude}`; +}; +var transformLngLat = (lngLat) => { + if (lngLat) { + const lngLatArr = lngLat ? lngLat.split(",") : []; + const longitude = Number(lngLatArr[0]); + const latitude = Number(lngLatArr[1]); + if (lngLatArr.length < 2) { + return null; + } + return { longitude, latitude }; + } + return null; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + fixedLngLat, + transformLngLat +}); diff --git a/packages/func/lib/math/index.d.ts b/packages/func/lib/math/index.d.ts new file mode 100644 index 0000000..1ea0b01 --- /dev/null +++ b/packages/func/lib/math/index.d.ts @@ -0,0 +1,70 @@ +import { IOdRectOrigin, Rect } from '@zhst/types'; +export declare const ALGORITHM_VERSION: { + 7: string; + 4: string; + 6: string; +}; +export declare const algorithmVersions: string[]; +export declare const getBikeExtendRect: (rect: Rect, maxW: number) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getOtherExtendRect: (srcRect: Rect, maxW: number, maxH: number, type: string) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getNormalization: (srcRect: Rect, maxW: number, maxH: number) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getExtendRect: (normalizationRect: Rect, imgW: number, imgH: number, type: string) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getTransformRect: (image: { + height: number; + width: number; +}, transform: { + translateX: any; + translateY: any; + scale: any; + rotate: any; +}, rect: Rect) => { + x: number; + y: number; + w: number; + h: number; +}; +export declare const getRotateImg: (image: HTMLImageElement, rotate: number) => File; +/** + * 格式化工具 + * @param originData + * @returns + */ +export declare const getOdRect: (originData: IOdRectOrigin) => { + x: any; + y: any; + w: any; + h: any; + id: any; + qualityScore: any; + algorithmVersion: string; + featureData: any; + objectRectIndex: number; + objectType: any; + objectId: any; + frameTimestamp: any; + sourceObjectId: any; + extendBox: any; +}[]; +export declare const getOdRectV2: (originData: { + odv2Result: any[]; +}) => any; diff --git a/packages/func/lib/math/index.js b/packages/func/lib/math/index.js new file mode 100644 index 0000000..85be6ff --- /dev/null +++ b/packages/func/lib/math/index.js @@ -0,0 +1,358 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/math/index.ts +var math_exports = {}; +__export(math_exports, { + ALGORITHM_VERSION: () => ALGORITHM_VERSION, + algorithmVersions: () => algorithmVersions, + getBikeExtendRect: () => getBikeExtendRect, + getExtendRect: () => getExtendRect, + getNormalization: () => getNormalization, + getOdRect: () => getOdRect, + getOdRectV2: () => getOdRectV2, + getOtherExtendRect: () => getOtherExtendRect, + getRotateImg: () => getRotateImg, + getTransformRect: () => getTransformRect +}); +module.exports = __toCommonJS(math_exports); +var import_lodash_es = require("lodash-es"); +var import_file = require("../file"); +var proto = { + Common: { + AlgorithmVersion: { + VERSION_REID_HEAD_ATTR: "形体", + VERSION_FACE: "人脸", + VERSION_NON_MOTOR_VEHICLE: "非机动车" + } + } +}; +var ALGORITHM_VERSION = { + ["7"]: "形体", + ["4"]: "人脸", + ["6"]: "非机动车" +}; +var algorithmVersions = [...Object.keys(ALGORITHM_VERSION)]; +var getBikeExtendRect = (rect, maxW) => { + const newRect = { ...rect }; + const oldY = (0, import_lodash_es.cloneDeep)(rect.y); + newRect.y = newRect.y - newRect.h < 0 ? 0 : newRect.y - newRect.h; + newRect.h += oldY - newRect.y; + let newX = Math.round(newRect.x - newRect.w * 0.15); + if (newX < 0) { + newX = 0; + } + let newW = newRect.x - newX + newRect.w + Math.round(newRect.w * 0.15); + if (newX + newW > maxW) { + newW = maxW - newX; + } + newRect.x = newX; + newRect.w = newW; + return newRect; +}; +var getOtherExtendRect = (srcRect, maxW, maxH, type) => { + const wExtendRadio = 0.25; + const upExtendRadio = 0.25; + const downExtendRadio = 0.25; + const fixPersonExtend = true; + let nx = 0; + let nw = 0; + nx = srcRect.x - Math.round(srcRect.w * wExtendRadio); + if (nx < 0) { + nx = 0; + } + nw = srcRect.x - nx + srcRect.w + Math.round(srcRect.w * wExtendRadio); + if (nx + nw > maxW) { + nw = maxW - nx; + } + let ny = 0; + let nh = 0; + ny = srcRect.y - Math.round(upExtendRadio * srcRect.h); + if (ny < 0) { + ny = 0; + } + nh = srcRect.y - ny + srcRect.h + Math.round(srcRect.h * downExtendRadio); + if (ny + nh > maxH) { + nh = maxH - ny; + } + let newRect = { + x: nx, + y: ny, + w: nw, + h: nh + }; + if ((type === proto.Common.AlgorithmVersion.VERSION_REID_HEAD_ATTR || type === proto.Common.AlgorithmVersion.VERSION_FACE) && fixPersonExtend) { + const fixW = Math.round(nh * 0.75); + if (nw < fixW) { + let newX = nx + Math.round(nw / 2 - 0.5 * fixW); + if (newX < 0) { + newX = 0; + } + let newW = fixW; + if (newW + newX > maxW) { + newW = maxW - newX; + } + newRect = { + x: newX, + y: ny, + w: newW, + h: nh + }; + } else if (nw > fixW) { + const fixH = Math.round(nw * 1.333); + let newY = ny + Math.round(nh / 2 - 0.5 * fixH); + if (newY < 0) { + newY = 0; + } + let newH = fixH; + if (newY + newH > maxH) { + newH = maxH - newY; + } + newRect = { + x: nx, + y: newY, + w: nw, + h: newH + }; + } + } + return newRect; +}; +var getNormalization = (srcRect, maxW, maxH) => { + const newRect = { + ...srcRect + }; + newRect.x = srcRect.x / maxW; + newRect.y = srcRect.y / maxH; + newRect.w = srcRect.w / maxW; + newRect.h = srcRect.h / maxH; + if (newRect.x + newRect.w > 1) { + newRect.w = 1 - newRect.x; + } + if (newRect.y + newRect.h > 1) { + newRect.h = 1 - newRect.y; + } + return newRect; +}; +var getExtendRect = (normalizationRect, imgW, imgH, type) => { + const rect = { + x: normalizationRect.x * imgW, + y: normalizationRect.y * imgH, + w: normalizationRect.w * imgW, + h: normalizationRect.h * imgH + }; + let newRect; + if (type === proto.Common.AlgorithmVersion.VERSION_NON_MOTOR_VEHICLE) { + newRect = getBikeExtendRect(rect, imgW); + } else { + newRect = getOtherExtendRect(rect, imgW, imgH, type); + } + newRect = getNormalization(newRect, imgW, imgH); + return newRect; +}; +var getTransformRect = (image, transform, rect) => { + const canvasRect = { + x: rect.x, + y: rect.y, + x2: rect.x + rect.w, + y2: rect.h + rect.y + }; + const { translateX, translateY, scale, rotate } = transform; + const originAxisRect = { + x: (canvasRect.x - translateX) / scale, + y: (canvasRect.y - translateY) / scale, + x2: (canvasRect.x2 - translateX) / scale, + y2: (canvasRect.y2 - translateY) / scale + }; + let imgAxisRect = originAxisRect; + if (rotate % 180 !== 0) { + const offsetX = -(image.height - image.width) / 2; + const offsetY = -(image.width - image.height) / 2; + imgAxisRect = { + x: originAxisRect.x - offsetX, + y: originAxisRect.y - offsetY, + x2: originAxisRect.x2 - offsetX, + y2: originAxisRect.y2 - offsetY + }; + } + let imgW = image.width; + let imgH = image.height; + if (rotate % 180 !== 0) { + [imgW, imgH] = [imgH, imgW]; + } + imgAxisRect.x = Math.min(imgW, Math.max(imgAxisRect.x, 0)); + imgAxisRect.y = Math.min(imgH, Math.max(imgAxisRect.y, 0)); + imgAxisRect.x2 = Math.min(imgW, Math.max(imgAxisRect.x2, 0)); + imgAxisRect.y2 = Math.min(imgH, Math.max(imgAxisRect.y2, 0)); + const endRect = { + x: imgAxisRect.x2 > imgAxisRect.x ? imgAxisRect.x : imgAxisRect.x2, + y: imgAxisRect.y2 > imgAxisRect.y ? imgAxisRect.y : imgAxisRect.y2, + w: Math.abs(imgAxisRect.x2 - imgAxisRect.x), + h: Math.abs(imgAxisRect.y2 - imgAxisRect.y) + }; + return getNormalization(endRect, imgW, imgH); +}; +var getRotateImg = (image, rotate) => { + var _a; + let imgW = image.width; + let imgH = image.height; + if (rotate % 180 !== 0) { + [imgW, imgH] = [imgH, imgW]; + } + const commonCanvas = document.createElement("canvas"); + commonCanvas.width = imgW; + commonCanvas.height = imgH; + commonCanvas.style.display = "none"; + document.body.appendChild(commonCanvas); + const commonCtx = commonCanvas.getContext("2d"); + commonCtx == null ? void 0 : commonCtx.save(); + if (rotate % 180 !== 0) { + commonCtx == null ? void 0 : commonCtx.translate((image.height - image.width) / 2, (image.width - image.height) / 2); + } + commonCtx == null ? void 0 : commonCtx.translate(image.width / 2, image.height / 2); + commonCtx == null ? void 0 : commonCtx.rotate(rotate / 180 * Math.PI); + commonCtx == null ? void 0 : commonCtx.translate(-image.width / 2, -image.height / 2); + commonCtx == null ? void 0 : commonCtx.drawImage(image, 0, 0); + commonCtx == null ? void 0 : commonCtx.restore(); + const dataUrl = commonCanvas.toDataURL("image/jpeg"); + const blobData = (0, import_file.dataURLToBlob)(dataUrl); + const file = new window.File([blobData], `${(/* @__PURE__ */ new Date()).getTime()}`, { + type: "image/jpeg" + }); + (_a = commonCanvas.parentNode) == null ? void 0 : _a.removeChild(commonCanvas); + return file; +}; +var getOdRect = (originData) => { + let data = (0, import_lodash_es.get)(originData, "objects", []).filter((v) => !(0, import_lodash_es.isNull)((0, import_lodash_es.get)(v, "infoOnSource.bboxInFrame.bboxRatio"))).map((v, index) => { + const rect = (0, import_lodash_es.get)(v, "infoOnSource.bboxInFrame.bboxRatio"); + const extendBox = (0, import_lodash_es.get)(v, "infoOnSource.bboxInFrame.extendBoxRatio"); + const frameTimestamp = (0, import_lodash_es.get)(v, "timestamp"); + const qualityScore = (0, import_lodash_es.get)(v, "qualityScore"); + const algorithmVersion = (0, import_lodash_es.get)(v, "objectType") === "OBJECT_TYPE_PEDESTRAIN" ? "VERSION_REID_HEAD_ATTR" : (0, import_lodash_es.get)(v, "objectType") === "OBJECT_TYPE_FACE" ? "VERSION_FACE" : "VERSION_REID_HEAD_ATTR"; + const featureData = (0, import_lodash_es.get)(v, "feature", []).filter( + (v2) => v2.type === "FEATURE_TYPE_BYTE" + ); + const objectRectIndex = algorithmVersion === "VERSION_FACE" ? 0 : 1; + const objectType = (0, import_lodash_es.get)(v, "objectType"); + const objectId = (0, import_lodash_es.get)(v, "objectIndex.objectId"); + const sourceObjectId = (0, import_lodash_es.get)(v, "sourceObjectId"); + return { + x: rect.x, + y: rect.y, + w: rect.w, + h: rect.h, + // faceCorrectImage: faceCorrectImage, + id: index, + qualityScore, + algorithmVersion, + featureData: (0, import_lodash_es.get)(featureData, "0.featureByte"), + objectRectIndex, + objectType, + objectId, + frameTimestamp, + sourceObjectId, + extendBox + }; + }); + if (data.length > 0) { + data = data.filter((v) => v.objectId !== "0"); + } else { + throw new Error("empty"); + } + return data; +}; +var getOdRectV2 = (originData) => { + const resp = originData.odv2Result[0]; + const subObjects = []; + const data = (0, import_lodash_es.get)(resp, "objects", []).filter((v) => !(0, import_lodash_es.isNull)((0, import_lodash_es.get)(v, "subObjects[0].infoOnSource.bboxInFrame.bboxRatio"))).map((v, index) => { + const rect = (0, import_lodash_es.get)(v, "infoOnSource.bboxInFrame.bboxRatio"); + const qualityScore = (0, import_lodash_es.get)(v, "qualityScore"); + const algorithmVersion = (0, import_lodash_es.get)(v, "objectType"); + const featrueData = (0, import_lodash_es.get)(v, "feature", []).filter( + (v2) => v2.name === "feature-body" || v2.name === "feature-face" + ); + const objectRectIndex = algorithmVersion === "OBJECT_TYPE_FACE" ? 0 : 1; + const objectType = (0, import_lodash_es.get)(v, "objectType"); + const objectId = (0, import_lodash_es.get)(v, "objectIndex.objectId"); + if ((0, import_lodash_es.get)(v, "subObjects", []).length) { + (0, import_lodash_es.get)(v, "subObjects", []).forEach((e) => { + const rect2 = (0, import_lodash_es.get)(e, "infoOnSource.bboxInFrame.bboxRatio"); + const qualityScore2 = (0, import_lodash_es.get)(e, "qualityScore"); + const algorithmVersion2 = (0, import_lodash_es.get)(e, "objectType"); + const featrueData2 = (0, import_lodash_es.get)(e, "feature", []).filter( + (v2) => v2.name === "feature-body" || v2.name === "feature-face" + ); + const objectRectIndex2 = algorithmVersion2 === "OBJECT_TYPE_FACE" ? 0 : 1; + const objectType2 = (0, import_lodash_es.get)(e, "objectType"); + const objectId2 = (0, import_lodash_es.get)(e, "objectIndex.objectId"); + subObjects.push({ + x: rect2.x, + y: rect2.y, + w: rect2.w, + h: rect2.h, + id: index, + qualityScore: qualityScore2, + algorithmVersion: algorithmVersion2, + featrueData: featrueData2.length ? featrueData2[0].featureByte : "", + objectRectIndex: objectRectIndex2, + objectType: objectType2, + objectId: objectId2 + }); + }); + } + return { + x: rect.x, + y: rect.y, + w: rect.w, + h: rect.h, + id: index, + qualityScore, + algorithmVersion, + featrueData: featrueData[0].featureByte, + objectRectIndex, + objectType, + objectId + }; + }); + const brr = data.concat(subObjects).map((v, vs) => { + if (String(v.id)) { + v.id = vs; + } + return v; + }); + if (brr.length > 0) { + console.log(brr, "data111"); + } else { + throw new Error("empty"); + } + console.log(brr); + return brr; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ALGORITHM_VERSION, + algorithmVersions, + getBikeExtendRect, + getExtendRect, + getNormalization, + getOdRect, + getOdRectV2, + getOtherExtendRect, + getRotateImg, + getTransformRect +}); diff --git a/packages/func/lib/number/index.d.ts b/packages/func/lib/number/index.d.ts new file mode 100644 index 0000000..b8e65be --- /dev/null +++ b/packages/func/lib/number/index.d.ts @@ -0,0 +1,14 @@ +/** + * 设置数据的精度 + * @param originNumber + * @param accuracy 精度 以原点为中心向左为正,向右为负, + * @param isCeil 是否为向上取整 + * @returns number + */ +export declare const setNumberAccuracy: (originNumber: number, accuracy?: number, isCeil?: boolean) => number; +/** + * 获取数字 + * @param number 需要校验的数值 + * @returns @number + */ +export declare const toRealNumber: (number: any) => any; diff --git a/packages/func/lib/number/index.js b/packages/func/lib/number/index.js new file mode 100644 index 0000000..371a003 --- /dev/null +++ b/packages/func/lib/number/index.js @@ -0,0 +1,53 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/number/index.ts +var number_exports = {}; +__export(number_exports, { + setNumberAccuracy: () => setNumberAccuracy, + toRealNumber: () => toRealNumber +}); +module.exports = __toCommonJS(number_exports); +var setNumberAccuracy = (originNumber, accuracy = 0, isCeil = true) => { + if (originNumber === 0) { + return 0; + } + let returnData = 0; + if (isCeil) { + returnData = Math.ceil(originNumber / Math.pow(10, accuracy)) * Math.pow(10, accuracy); + } else { + returnData = Math.floor(originNumber / Math.pow(10, accuracy)) * Math.pow(10, accuracy); + } + if (accuracy < 0) { + returnData = Number(returnData.toFixed(-accuracy)); + } else { + returnData = Number(returnData.toFixed(0)); + } + return returnData; +}; +var toRealNumber = (number) => { + if (isNaN(number) || number === Infinity) { + return 0; + } else + return number; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + setNumberAccuracy, + toRealNumber +}); diff --git a/packages/func/lib/performance/index.d.ts b/packages/func/lib/performance/index.d.ts new file mode 100644 index 0000000..22dd838 --- /dev/null +++ b/packages/func/lib/performance/index.d.ts @@ -0,0 +1 @@ +export declare const speedConvert: (bps: number, contertUnit?: number) => string; diff --git a/packages/func/lib/performance/index.js b/packages/func/lib/performance/index.js new file mode 100644 index 0000000..1d12f21 --- /dev/null +++ b/packages/func/lib/performance/index.js @@ -0,0 +1,41 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/performance/index.ts +var performance_exports = {}; +__export(performance_exports, { + speedConvert: () => speedConvert +}); +module.exports = __toCommonJS(performance_exports); +var speedConvert = (bps, contertUnit = 8) => { + if (bps === void 0) + return `0KB/s`; + const byte = bps / contertUnit; + if (bps > 1024 * 1024 * 1024) { + return `${(byte / 1024 / 1024 / 1024).toFixed(2)}GB/s`; + } else if (byte > 1024 * 1024) { + return `${(byte / 1024 / 1024).toFixed(2)}MB/s`; + } else if (byte > 1024) { + return `${(byte / 1024).toFixed(2)}KB/s`; + } + return `${byte}KB/s`; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + speedConvert +}); diff --git a/packages/func/lib/string/index.d.ts b/packages/func/lib/string/index.d.ts new file mode 100644 index 0000000..a209796 --- /dev/null +++ b/packages/func/lib/string/index.d.ts @@ -0,0 +1,7 @@ +export declare const getStrLength: (str: string) => number; +/** + * js截取字符串,中英文都能用 + * @param str:需要截取的字符串 + * @param len: 需要截取的长度 + */ +export declare const cutStr: (str: string, len: number) => string | String | undefined; diff --git a/packages/func/lib/string/index.js b/packages/func/lib/string/index.js new file mode 100644 index 0000000..4297b5a --- /dev/null +++ b/packages/func/lib/string/index.js @@ -0,0 +1,62 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/string/index.ts +var string_exports = {}; +__export(string_exports, { + cutStr: () => cutStr, + getStrLength: () => getStrLength +}); +module.exports = __toCommonJS(string_exports); +var getStrLength = function(str) { + var realLength = 0, len = str.length, charCode = -1; + for (var i = 0; i < len; i++) { + charCode = str.charCodeAt(i); + if (charCode >= 0 && charCode <= 128) + realLength += 1; + else + realLength += 2; + } + return realLength; +}; +var cutStr = function cutstr(str, len) { + var str_length = 0; + var str_len = 0; + let str_cut = new String(); + str_len = str.length; + for (var i = 0; i < str_len; i++) { + let a = str.charAt(i); + str_length++; + if (escape(a).length > 4) { + str_length++; + } + str_cut = str_cut.concat(a); + if (str_length >= len) { + str_cut = str_cut.concat("..."); + return str_cut; + } + } + if (str_length < len) { + return str; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + cutStr, + getStrLength +}); diff --git a/packages/func/lib/time/index.d.ts b/packages/func/lib/time/index.d.ts new file mode 100644 index 0000000..28b4d03 --- /dev/null +++ b/packages/func/lib/time/index.d.ts @@ -0,0 +1,11 @@ +export declare const formateDuration: (diff: number) => string; +export declare function generateTime(): { + startDateTime: number; + endDateTime: number; +}; +/** + * 格式化时间为 00:00 + * @param seconds 时间,单位秒 + * @returns + */ +export declare function formatDurationTime(seconds: number): string; diff --git a/packages/func/lib/time/index.js b/packages/func/lib/time/index.js new file mode 100644 index 0000000..cf77388 --- /dev/null +++ b/packages/func/lib/time/index.js @@ -0,0 +1,73 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/time/index.ts +var time_exports = {}; +__export(time_exports, { + formatDurationTime: () => formatDurationTime, + formateDuration: () => formateDuration, + generateTime: () => generateTime +}); +module.exports = __toCommonJS(time_exports); +var import_dayjs = __toESM(require("dayjs")); +var formateDuration = (diff) => { + var days = Math.floor(diff / (24 * 3600 * 1e3)); + var leave1 = diff % (24 * 3600 * 1e3); + var hours = Math.floor(leave1 / (3600 * 1e3)); + var leave2 = leave1 % (3600 * 1e3); + var minutes = Math.floor(leave2 / (60 * 1e3)); + var leave3 = leave2 % (60 * 1e3); + var seconds = Math.round(leave3 / 1e3); + var returnStr = seconds + "秒"; + if (minutes > 0) { + returnStr = minutes + "分"; + } + if (hours > 0) { + returnStr = hours + "小时"; + } + if (days > 0) { + returnStr = days + "天"; + } + return returnStr; +}; +function generateTime() { + let endDateTime = (0, import_dayjs.default)().endOf("day").unix(); + let startDateTime = (0, import_dayjs.default)().startOf("day").unix(); + return { startDateTime, endDateTime }; +} +function formatDurationTime(seconds) { + var minutes = Math.floor(seconds / 60) || 0; + var remainingSeconds = Math.floor(seconds % 60); + return (minutes < 10 ? `0${minutes}` : minutes) + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + formatDurationTime, + formateDuration, + generateTime +}); diff --git a/packages/func/lib/upload/index.d.ts b/packages/func/lib/upload/index.d.ts new file mode 100644 index 0000000..8c370db --- /dev/null +++ b/packages/func/lib/upload/index.d.ts @@ -0,0 +1,8 @@ +type uploadOption = { + bucket?: string; + dir?: string; + withSuFuffix?: boolean; +}; +export declare const commonUpload: (file: File, option: uploadOption | undefined, type: string) => Promise; +export declare const upload: (file: File, option?: uploadOption) => Promise; +export {}; diff --git a/packages/func/lib/upload/index.js b/packages/func/lib/upload/index.js new file mode 100644 index 0000000..0c549fb --- /dev/null +++ b/packages/func/lib/upload/index.js @@ -0,0 +1,90 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/upload/index.ts +var upload_exports = {}; +__export(upload_exports, { + commonUpload: () => commonUpload, + upload: () => upload +}); +module.exports = __toCommonJS(upload_exports); +var import_dayjs = __toESM(require("dayjs")); +var import_utils = require("../utils"); +var import_base_64 = __toESM(require("base-64")); +var import_uuid = require("uuid"); +var import_lodash_es = require("lodash-es"); +var import_request = __toESM(require("@zhst/request")); +var defaultBucket = "public"; +var commonUpload = async (file, option = {}, type) => { + const { bucket = defaultBucket, dir = "file", withSuFuffix = false } = option; + const prefix = `${(0, import_dayjs.default)().format("YYYYMMDD")}`; + const fileSuffix = withSuFuffix ? (0, import_utils.getFileSuffix)((0, import_lodash_es.get)(file, "name")) : ""; + const fileType = file["type"].split("/", 2); + let imageSuffix = ""; + if (fileType["0"] === "image") { + imageSuffix = (0, import_utils.getImageSuffixByFileType)(fileType["1"]); + } + const key = `${prefix}/${dir ? `${dir}/` : ""}${(0, import_uuid.v4)()}${!fileSuffix ? "" : `.${fileSuffix}`}`; + let imgKey = `${bucket}_${bucket}_${key}${imageSuffix}`; + if (type === "upload") { + imgKey = `v1_${import_base_64.default.encode(imgKey)}`; + return new Promise((resolve) => { + const reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = async () => { + var _a; + if (reader.result) { + await (0, import_request.default)({ + method: "PUT", + url: "/singer.FileServerService/PutObject", + data: { + version: 1, + bucket: defaultBucket, + objectName: `${bucket}_${key}${imageSuffix}`, + // fileData: reader.result, + putObjectOption: { + contentType: file.type + }, + // @ts-ignore + fileDataBase64: (_a = reader.result) == null ? void 0 : _a.split(";base64,")[1] + } + }); + resolve(imgKey); + } + }; + }); + } +}; +var upload = async (file, option = {}) => { + return await commonUpload(file, option, "upload"); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + commonUpload, + upload +}); diff --git a/packages/func/lib/utils/index.d.ts b/packages/func/lib/utils/index.d.ts new file mode 100644 index 0000000..4a5e574 --- /dev/null +++ b/packages/func/lib/utils/index.d.ts @@ -0,0 +1,36 @@ +export { default as isChrome } from './isChrome'; +export declare const matchS3Prefix: (str: string) => boolean; +/** + * 通过文件名获取文件类型 + * @param fileName 文件名称 + * @returns 文件类型 + */ +export declare const getFileSuffix: (fileName: string) => string; +/** + * 通过类型获取文件名 + * @param type 类型 + * @returns + */ +export declare const getImageSuffixByFileType: (type: string) => string; +export declare function getChromeVersion(): number | false; +export declare const nextTick: (func: (value: void) => void | PromiseLike) => void; +export declare const loop: (items: string | any[], callback: (arg0: any) => any) => void; +export declare const addEventListenerWrapper: (target: any, eventType: string, cb: any, option?: any) => { + remove: () => void; +}; +/** + * Get transforms base on the given object. + * @param {Object} obj - The target object. + * @returns {string} A string contains transform values. + */ +export declare function getTransforms({ rotate, scaleX, scaleY, translateX, translateY, }: { + rotate?: number; + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; +}): { + WebkitTransform: string; + msTransform: string; + transform: string; +}; diff --git a/packages/func/lib/utils/index.js b/packages/func/lib/utils/index.js new file mode 100644 index 0000000..78022ad --- /dev/null +++ b/packages/func/lib/utils/index.js @@ -0,0 +1,171 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + addEventListenerWrapper: () => addEventListenerWrapper, + getChromeVersion: () => getChromeVersion, + getFileSuffix: () => getFileSuffix, + getImageSuffixByFileType: () => getImageSuffixByFileType, + getTransforms: () => getTransforms, + isChrome: () => import_isChrome.default, + loop: () => loop, + matchS3Prefix: () => matchS3Prefix, + nextTick: () => nextTick +}); +module.exports = __toCommonJS(utils_exports); +var import_lodash_es = require("lodash-es"); +var import_react_dom = __toESM(require("react-dom")); +var import_isChrome = __toESM(require("./isChrome")); +var matchS3Prefix = (str) => { + return /^v[0-9]_/.test(str); +}; +var getFileSuffix = (fileName) => { + const splitArr = fileName.split("."); + return splitArr.length < 2 ? "" : splitArr[splitArr.length - 1]; +}; +var getImageSuffixByFileType = (type) => { + let imageSuffix = ""; + switch (type) { + case "jpeg": { + imageSuffix = ".jpg"; + break; + } + case "gif": { + imageSuffix = ".gif"; + break; + } + case "png": { + imageSuffix = ".png"; + break; + } + case "vnd.wap.wbmp": { + imageSuffix = ".wbmp"; + break; + } + case "x-up-wpng": { + imageSuffix = ".wpng"; + break; + } + case "nbmp": { + imageSuffix = ".nbmp"; + break; + } + } + return imageSuffix; +}; +function getChromeVersion() { + const arr = navigator.userAgent.split(" "); + let chromeVersion = ""; + for (let i = 0; i < arr.length; i++) { + if (/chrome/i.test(arr[i])) + chromeVersion = arr[i]; + } + if (chromeVersion) { + return Number(chromeVersion.split("/")[1].split(".")[0]); + } else { + return false; + } +} +var nextTick = (func) => { + if (queueMicrotask) { + queueMicrotask(func); + return; + } + Promise.resolve().then(func); +}; +var loop = (items, callback) => { + for (let i = 0; i < items.length; i++) { + const element = items[i]; + let isBreak = callback(element); + if (isBreak) { + return; + } + if (element["children"]) { + loop(element["children"], callback); + } + } +}; +var addEventListenerWrapper = (target, eventType, cb, option) => { + const callback = import_react_dom.default.unstable_batchedUpdates ? function run(e) { + import_react_dom.default.unstable_batchedUpdates(cb, e); + } : cb; + if (target.addEventListener) { + target.addEventListener(eventType, callback, option); + } + return { + remove: () => { + if (target.removeEventListener) { + target.removeEventListener(eventType, callback); + } + } + }; +}; +function getTransforms({ + rotate, + scaleX, + scaleY, + translateX, + translateY +}) { + const values = []; + if ((0, import_lodash_es.isNumber)(translateX) && translateX !== 0) { + values.push(`translateX(${translateX}px)`); + } + if ((0, import_lodash_es.isNumber)(translateY) && translateY !== 0) { + values.push(`translateY(${translateY}px)`); + } + if ((0, import_lodash_es.isNumber)(rotate) && rotate !== 0) { + values.push(`rotate(${rotate}deg)`); + } + if ((0, import_lodash_es.isNumber)(scaleX) && scaleX !== 1) { + values.push(`scaleX(${scaleX})`); + } + if ((0, import_lodash_es.isNumber)(scaleY) && scaleY !== 1) { + values.push(`scaleY(${scaleY})`); + } + const transform = values.length ? values.join(" ") : "none"; + return { + WebkitTransform: transform, + msTransform: transform, + transform + }; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + addEventListenerWrapper, + getChromeVersion, + getFileSuffix, + getImageSuffixByFileType, + getTransforms, + isChrome, + loop, + matchS3Prefix, + nextTick +}); diff --git a/packages/func/lib/utils/isChrome.d.ts b/packages/func/lib/utils/isChrome.d.ts new file mode 100644 index 0000000..2d07ceb --- /dev/null +++ b/packages/func/lib/utils/isChrome.d.ts @@ -0,0 +1,3 @@ +export declare const isBrowser: boolean; +declare const isChrome: () => boolean; +export default isChrome; diff --git a/packages/func/lib/utils/isChrome.js b/packages/func/lib/utils/isChrome.js new file mode 100644 index 0000000..4ad2681 --- /dev/null +++ b/packages/func/lib/utils/isChrome.js @@ -0,0 +1,42 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils/isChrome.ts +var isChrome_exports = {}; +__export(isChrome_exports, { + default: () => isChrome_default, + isBrowser: () => isBrowser +}); +module.exports = __toCommonJS(isChrome_exports); +var isBrowser = !!(typeof window !== "undefined" && window.document && window.document.createElement); +var isChrome = () => { + const winNav = isBrowser && window.navigator; + const vendorName = winNav && (winNav == null ? void 0 : winNav.vendor); + const userAgent = winNav && winNav.userAgent; + const isChromium = isBrowser && typeof chrome !== "undefined"; + const isOpera = isBrowser && typeof opr !== "undefined"; + const isIEedge = userAgent && userAgent.indexOf("Edge") > -1; + const isIOSChrome = !!(userAgent && userAgent.match("CriOS")); + const isDesktopChrome = isChromium && vendorName === "Google Inc." && !isOpera && !isIEedge; + return isIOSChrome || isDesktopChrome; +}; +var isChrome_default = isChrome; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + isBrowser +}); diff --git a/packages/func/package.json b/packages/func/package.json index 83e18e6..248ca30 100644 --- a/packages/func/package.json +++ b/packages/func/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/func", - "version": "0.2.4", + "version": "0.3.0", "description": "函数合集", "keywords": [ "hooks" diff --git a/packages/func/src/file/index.ts b/packages/func/src/file/index.ts index 20b93ec..ea7fbd4 100644 --- a/packages/func/src/file/index.ts +++ b/packages/func/src/file/index.ts @@ -275,9 +275,13 @@ export const generateImg: (imgKey: string, host?: string) => string = (_imgKey, //判空 if (!imgKey) return '' - if (/^(http:|https:)/.test(imgKey)) { + + if (/(http|https):\/\/([\w.]+\/?)\S*/ig.test(imgKey)) { return imgKey; } + + console.log('imgKey', imgKey) + try { if (matchS3Prefix(imgKey)) { imgKey = base64DecodeImageKey(imgKey); diff --git a/packages/func/src/math/index.ts b/packages/func/src/math/index.ts index fb4d317..9b80d2f 100644 --- a/packages/func/src/math/index.ts +++ b/packages/func/src/math/index.ts @@ -40,7 +40,7 @@ export const getBikeExtendRect = (rect: Rect, maxW: number) => { return newRect; }; -export const getOtherExtendRect = (srcRect, maxW, maxH, type) => { +export const getOtherExtendRect = (srcRect: Rect, maxW: number, maxH: number, type: string) => { const wExtendRadio = 0.25; const upExtendRadio = 0.25; const downExtendRadio = 0.25; @@ -296,24 +296,23 @@ export const getOdRect = (originData: IOdRectOrigin) => { //档案库od export const getOdRectV2 = (originData: { odv2Result: any[]; }) => { - // const fileKey = 'v1_' + window.btoa('public_' + imgKey.split('public/')[1]); const resp = originData.odv2Result[0]; const subObjects: { x: any; y: any; w: any; h: any; id: any; qualityScore: any; algorithmVersion: any; featrueData: any; objectRectIndex: number; objectType: any; objectId: any; }[] = []; //形体 const data = get(resp, 'objects', []) - .filter((v) => !isNull(get(v, 'subObjects[0].infoOnSource.bboxInFrame.bboxRatio'))) - .map((v, index) => { + .filter((v: any) => !isNull(get(v, 'subObjects[0].infoOnSource.bboxInFrame.bboxRatio'))) + .map((v: any, index: any) => { const rect = get(v, 'infoOnSource.bboxInFrame.bboxRatio'); const qualityScore = get(v, 'qualityScore'); const algorithmVersion = get(v, 'objectType'); const featrueData = get(v, 'feature', []).filter( - (v) => v.name === 'feature-body' || v.name === 'feature-face' + (v: { name: string; }) => v.name === 'feature-body' || v.name === 'feature-face' ); const objectRectIndex = algorithmVersion === 'OBJECT_TYPE_FACE' ? 0 : 1; const objectType = get(v, 'objectType'); const objectId = get(v, 'objectIndex.objectId'); //如果存在subObjects的数组不为null表示形体里面带人脸,人脸的od框也要显示出来 if (get(v, 'subObjects', []).length) { - get(v, 'subObjects', []).forEach((e) => { + get(v, 'subObjects', []).forEach((e: any) => { const rect = get(e, 'infoOnSource.bboxInFrame.bboxRatio'); const qualityScore = get(e, 'qualityScore'); const algorithmVersion = get(e, 'objectType'); @@ -366,83 +365,3 @@ export const getOdRectV2 = (originData: { odv2Result: any[]; }) => { console.log(brr); return brr; }; - -//获取图片 - -export const getFileByRect = async (img: any, odRect: Rect) => { - let image; - if (isString(img)) { - const url = generateImg(img); - console.log(url, '获取图片'); - image = await urlToImg(url); - console.log(image, '获取的图片'); - } else { - image = img; - } - const commonCanvas = document.createElement('canvas'); - commonCanvas.width = odRect.w * image.width; - commonCanvas.height = odRect.h * image.height; - commonCanvas.style.display = 'none'; - document.body.appendChild(commonCanvas); - const commonCtx = commonCanvas.getContext('2d'); - commonCtx?.translate(-odRect.x * image.width, -odRect.y * image.height); - commonCtx?.drawImage(image, 0, 0); - const base64 = commonCanvas.toDataURL('image/jpeg'); - const blobData = dataURLToBlob(base64); - commonCanvas?.parentNode?.removeChild(commonCanvas); - const file = new window.File([blobData], `${new Date().getTime()}`, { - type: 'image/jpeg', - }); - return file; -}; - - -/** - * Get transforms base on the given object. - * @param {Object} obj - The target object. - * @returns {string} A string contains transform values. - */ -export function getTransforms({ - rotate, - scaleX, - scaleY, - translateX, - translateY, -}: { - rotate?: number; - scaleX?: number; - scaleY?: number; - translateX?: number; - translateY?: number; -}) { - const values = []; - - if (isNumber(translateX) && translateX !== 0) { - values.push(`translateX(${translateX}px)`); - } - - if (isNumber(translateY) && translateY !== 0) { - values.push(`translateY(${translateY}px)`); - } - - // Rotate should come first before scale to match orientation transform - if (isNumber(rotate) && rotate !== 0) { - values.push(`rotate(${rotate}deg)`); - } - - if (isNumber(scaleX) && scaleX !== 1) { - values.push(`scaleX(${scaleX})`); - } - - if (isNumber(scaleY) && scaleY !== 1) { - values.push(`scaleY(${scaleY})`); - } - - const transform = values.length ? values.join(' ') : 'none'; - - return { - WebkitTransform: transform, - msTransform: transform, - transform, - }; -} diff --git a/packages/func/src/upload/index.ts b/packages/func/src/upload/index.ts index 1224ba3..5d4b5ff 100644 --- a/packages/func/src/upload/index.ts +++ b/packages/func/src/upload/index.ts @@ -43,6 +43,7 @@ export const commonUpload = async (file: File, option: uploadOption = {}, type: putObjectOption: { contentType: file.type, }, + // @ts-ignore fileDataBase64: reader.result?.split(';base64,')[1], }, }); diff --git a/packages/func/src/utils/isChrome.ts b/packages/func/src/utils/isChrome.ts index e03a2f3..160b30c 100644 --- a/packages/func/src/utils/isChrome.ts +++ b/packages/func/src/utils/isChrome.ts @@ -1,8 +1,12 @@ -export const isBrowser = !!(typeof window !== 'undefined' && window); +export const isBrowser = !!( + typeof window !== 'undefined' && + window.document && + window.document.createElement +); const isChrome = () =>{ const winNav = isBrowser && window.navigator; - const vendorName = winNav && winNav.vendor; + const vendorName = winNav && winNav?.vendor; const userAgent = winNav && winNav.userAgent; //@ts-ignore diff --git a/packages/hooks/CHANGELOG.md b/packages/hooks/CHANGELOG.md index 299ee29..0b60bc9 100644 --- a/packages/hooks/CHANGELOG.md +++ b/packages/hooks/CHANGELOG.md @@ -1,5 +1,16 @@ # @zhst/hooks +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + +### Patch Changes + +- Updated dependencies + - @zhst/func@0.3.0 + ## 0.2.4 ### Patch Changes diff --git a/packages/hooks/package.json b/packages/hooks/package.json index 1c0dba5..b872541 100644 --- a/packages/hooks/package.json +++ b/packages/hooks/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/hooks", - "version": "0.2.4", + "version": "0.3.0", "description": "hooks合集", "keywords": [ "hooks" diff --git a/packages/material/CHANGELOG.md b/packages/material/CHANGELOG.md index 444b4f0..ee89e63 100644 --- a/packages/material/CHANGELOG.md +++ b/packages/material/CHANGELOG.md @@ -1,5 +1,19 @@ # @zhst/biz +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + +### Patch Changes + +- Updated dependencies + - @zhst/hooks@0.3.0 + - @zhst/func@0.3.0 + - @zhst/meta@0.3.0 + - @zhst/biz@0.3.0 + ## 0.2.4 ### Patch Changes diff --git a/packages/material/README.md b/packages/material/README.md index 23ba41e..96d7ea4 100644 --- a/packages/material/README.md +++ b/packages/material/README.md @@ -1,16 +1,20 @@ +:::warning{title=待开始} +目前项目正在如火如荼的筹备中... +::: + ## 介绍 -业务库 +物料库,每一个物料都是单独存在的个体,不需要任何依赖,就能形成一个页面,甚至一个项目 ## 安装 -> pnpm install @zhst/biz +> pnpm install @zhst/material ## 使用 ```jsx import React from 'react'; -import { Demo } from '@zhst/biz' +import { Demo } from '@zhst/material' export default () => ``` diff --git a/packages/material/es/Demo/index.d.ts b/packages/material/es/Demo/index.d.ts new file mode 100644 index 0000000..bcc157c --- /dev/null +++ b/packages/material/es/Demo/index.d.ts @@ -0,0 +1,3 @@ +import React from 'react'; +declare const _default: () => React.JSX.Element; +export default _default; diff --git a/packages/material/es/Demo/index.js b/packages/material/es/Demo/index.js new file mode 100644 index 0000000..9c21809 --- /dev/null +++ b/packages/material/es/Demo/index.js @@ -0,0 +1,4 @@ +import React from 'react'; +export default (function () { + return /*#__PURE__*/React.createElement("div", null, "hi"); +}); \ No newline at end of file diff --git a/packages/material/es/index.d.ts b/packages/material/es/index.d.ts new file mode 100644 index 0000000..31f4c03 --- /dev/null +++ b/packages/material/es/index.d.ts @@ -0,0 +1 @@ +export { default as Demo } from './Demo'; diff --git a/packages/material/es/index.js b/packages/material/es/index.js new file mode 100644 index 0000000..dd020e4 --- /dev/null +++ b/packages/material/es/index.js @@ -0,0 +1 @@ +export { default as Demo } from "./Demo"; \ No newline at end of file diff --git a/packages/material/lib/Demo/index.d.ts b/packages/material/lib/Demo/index.d.ts new file mode 100644 index 0000000..bcc157c --- /dev/null +++ b/packages/material/lib/Demo/index.d.ts @@ -0,0 +1,3 @@ +import React from 'react'; +declare const _default: () => React.JSX.Element; +export default _default; diff --git a/packages/material/lib/Demo/index.js b/packages/material/lib/Demo/index.js new file mode 100644 index 0000000..09e6968 --- /dev/null +++ b/packages/material/lib/Demo/index.js @@ -0,0 +1,38 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/Demo/index.tsx +var Demo_exports = {}; +__export(Demo_exports, { + default: () => Demo_default +}); +module.exports = __toCommonJS(Demo_exports); +var import_react = __toESM(require("react")); +var Demo_default = () => { + return /* @__PURE__ */ import_react.default.createElement("div", null, "hi"); +}; diff --git a/packages/material/lib/index.d.ts b/packages/material/lib/index.d.ts new file mode 100644 index 0000000..31f4c03 --- /dev/null +++ b/packages/material/lib/index.d.ts @@ -0,0 +1 @@ +export { default as Demo } from './Demo'; diff --git a/packages/material/lib/index.js b/packages/material/lib/index.js new file mode 100644 index 0000000..7462083 --- /dev/null +++ b/packages/material/lib/index.js @@ -0,0 +1,39 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.tsx +var src_exports = {}; +__export(src_exports, { + Demo: () => import_Demo.default +}); +module.exports = __toCommonJS(src_exports); +var import_Demo = __toESM(require("./Demo")); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Demo +}); diff --git a/packages/material/package.json b/packages/material/package.json index 93f39cf..b6785eb 100644 --- a/packages/material/package.json +++ b/packages/material/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/material", - "version": "0.2.4", + "version": "0.3.0", "description": "物料库", "keywords": [ "business", diff --git a/packages/material/src/Demo/index.tsx b/packages/material/src/Demo/index.tsx index 7545062..614fa16 100644 --- a/packages/material/src/Demo/index.tsx +++ b/packages/material/src/Demo/index.tsx @@ -1,12 +1,8 @@ import React from 'react' -import { Button } from '@zhst/meta' -import { useThrottleFn } from '@zhst/hooks' export default () => { - const { run } = useThrottleFn(() => console.log('123')) - return ( - +
    hi
    ) } diff --git a/packages/meta/CHANGELOG.md b/packages/meta/CHANGELOG.md index 19b1dcf..8d08acb 100644 --- a/packages/meta/CHANGELOG.md +++ b/packages/meta/CHANGELOG.md @@ -1,5 +1,17 @@ # @zhst/utils +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + +### Patch Changes + +- Updated dependencies + - @zhst/hooks@0.3.0 + - @zhst/func@0.3.0 + ## 0.2.4 ### Patch Changes diff --git a/packages/meta/es/BigImagePreview/BigImagePreview.d.ts b/packages/meta/es/BigImagePreview/BigImagePreview.d.ts new file mode 100644 index 0000000..45d7836 --- /dev/null +++ b/packages/meta/es/BigImagePreview/BigImagePreview.d.ts @@ -0,0 +1,35 @@ +import React, { ReactElement } from 'react'; +import { type Rect, type IScreenshotButtonProp, type AlignType, type ViewOption, type IOdRectOrigin } from '@zhst/types'; +import './index.less'; +export interface ImgViewProps extends React.HTMLAttributes { + dataSource: Array<{ + url?: string; + imageKey: string; + attachImg?: Array<{ + label: string; + url: string; + }>; + odRect?: Rect; + score?: number; + showScore?: boolean; + cameraPosition?: string; + time?: string | number; + objects: any[]; + }>; + showAttachImgLabel: boolean; + showOpt: boolean; + width?: string | number; + height?: string | number; + screenshotButtonAlign: AlignType; + screenshotButtonRender: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; + hideLeftTopBtn?: boolean; + showScore?: boolean; + viewOption?: ViewOption; + objects: IOdRectOrigin[]; +} +export interface ImgViewRef { + imgInsRef: React.MutableRefObject; + setShowCrop: React.Dispatch>; +} +export declare const BigImagePreview: React.ForwardRefExoticComponent>; +export default BigImagePreview; diff --git a/packages/meta/es/BigImagePreview/BigImagePreview.js b/packages/meta/es/BigImagePreview/BigImagePreview.js new file mode 100644 index 0000000..31fffcb --- /dev/null +++ b/packages/meta/es/BigImagePreview/BigImagePreview.js @@ -0,0 +1,578 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +import React, { useEffect, useState, useCallback, useRef, useImperativeHandle } from 'react'; +import classNames from 'classnames'; +import { useLatest } from '@zhst/hooks'; +import { get, pick, isNull, generateImg, dataURLToBlob, getOdRect, getExtendRect, getTransformRect, getRotateImg, getTransforms, addEventListenerWrapper, upload, getFileByRect } from '@zhst/func'; +import Align from 'rc-align'; +import { Button, Empty } from 'antd'; +import Icon from "../iconfont"; +import { Cropper, Viewer, EVENT_VIEWER_TRANSFORM_CHANGE, EVENT_VIEWER_READY, EVENT_CROP_START, EVENT_CROP_END } from "../ImageEditor"; +import BtnGroup from "./components/BtnGroup"; +import "./index.less"; +import getScreenshotButtonRender from "./components/ScreenhotButtons"; +import { defaultAlignOption, CROP_TYPE } from "../utils/constants"; +var componentName = "zhst-image__img-view"; +var cropBtnDataSource = [{ + key: 'close', + icon: 'icon-danchuangguanbi', + title: '退出' +}, { + key: 'autoCrop', + icon: 'icon-zidong', + title: '智能框选' +}, { + key: 'customCrop', + icon: 'icon-shoudong', + title: '手动框选' +}]; +var operateBtnDataSource = [{ + key: 'zoomOut', + icon: 'icon-fangda', + title: '放大' +}, { + key: 'zoomIn', + icon: 'icon-suoxiao', + title: '缩小' +}, { + key: 'reset', + icon: 'icon-zhongzhi3', + title: '重置图片' +}]; +export var BigImagePreview = /*#__PURE__*/React.forwardRef(function (props, ref) { + var _dataSource$currentIn2, _dataSource$currentIn3; + var _props$dataSource = props.dataSource, + dataSource = _props$dataSource === void 0 ? [] : _props$dataSource, + width = props.width, + height = props.height, + _props$showScore = props.showScore, + showScore = _props$showScore === void 0 ? true : _props$showScore, + _props$objects = props.objects, + objects = _props$objects === void 0 ? [] : _props$objects, + _props$showOpt = props.showOpt, + showOpt = _props$showOpt === void 0 ? false : _props$showOpt, + _props$showAttachImgL = props.showAttachImgLabel, + showAttachImgLabel = _props$showAttachImgL === void 0 ? true : _props$showAttachImgL, + _props$screenshotButt = props.screenshotButtonAlign, + screenshotButtonAlign = _props$screenshotButt === void 0 ? defaultAlignOption : _props$screenshotButt, + _props$screenshotButt2 = props.screenshotButtonRender, + screenshotButtonRender = _props$screenshotButt2 === void 0 ? getScreenshotButtonRender({ + onBigImageActionClick: function onBigImageActionClick() {}, + disableBtn: [] + }) : _props$screenshotButt2, + _props$hideLeftTopBtn = props.hideLeftTopBtn, + hideLeftTopBtn = _props$hideLeftTopBtn === void 0 ? true : _props$hideLeftTopBtn, + _props$viewOption = props.viewOption, + viewOption = _props$viewOption === void 0 ? {} : _props$viewOption; + var imgContainerRef = React.useRef(null); + var _useState = useState(false), + _useState2 = _slicedToArray(_useState, 2), + isReady = _useState2[0], + setIsReady = _useState2[1]; + var _useState3 = useState(0), + _useState4 = _slicedToArray(_useState3, 2), + currentIndex = _useState4[0], + setCurrentIndex = _useState4[1]; + console.log('props', props); + var init = useCallback(function ($container) { + imgContainerRef.current = $container; + setIsReady(true); + }, []); + // ============================= viewer ========================= + var imgInsRef = useRef(null); + var _useState5 = useState(false), + _useState6 = _slicedToArray(_useState5, 2), + isImgReady = _useState6[0], + setIsImgReady = _useState6[1]; + useEffect(function () { + var _dataSource$currentIn; + console.log('123', 123); + if (!isReady || !(imgContainerRef !== null && imgContainerRef !== void 0 && imgContainerRef.current)) return; + var handleReady = addEventListenerWrapper(imgContainerRef.current, EVENT_VIEWER_READY, function () { + setIsImgReady(true); + }); + var handleTransformChange = addEventListenerWrapper(imgContainerRef.current, EVENT_VIEWER_TRANSFORM_CHANGE, function () {}); + imgInsRef.current = new Viewer(imgContainerRef.current, _objectSpread(_objectSpread({}, viewOption), {}, { + fitScaleAsMinScale: true, + image: generateImg((_dataSource$currentIn = dataSource[currentIndex]) === null || _dataSource$currentIn === void 0 ? void 0 : _dataSource$currentIn.imageKey) + })); + return function () { + var _imgInsRef$current, _imgInsRef$current$de; + handleReady === null || handleReady === void 0 || handleReady.remove(); + handleTransformChange === null || handleTransformChange === void 0 || handleTransformChange.remove(); + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current = imgInsRef.current) === null || _imgInsRef$current === void 0 || (_imgInsRef$current$de = _imgInsRef$current.destroy) === null || _imgInsRef$current$de === void 0 || _imgInsRef$current$de.call(_imgInsRef$current); + imgInsRef.current = null; + }; + }, [isReady, currentIndex]); + + // ============================= viewer操作按钮 ========================= + var handleOptClick = function handleOptClick(v) { + var _imgInsRef$current2, _imgInsRef$current2$s, _imgInsRef$current3, _imgInsRef$current3$s, _imgInsRef$current4, _imgInsRef$current4$r; + switch (v) { + case 'zoomOut': + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current2 = imgInsRef.current) === null || _imgInsRef$current2 === void 0 || (_imgInsRef$current2$s = _imgInsRef$current2.scaleTo) === null || _imgInsRef$current2$s === void 0 || _imgInsRef$current2$s.call(_imgInsRef$current2, 0.1); + break; + case 'zoomIn': + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current3 = imgInsRef.current) === null || _imgInsRef$current3 === void 0 || (_imgInsRef$current3$s = _imgInsRef$current3.scaleTo) === null || _imgInsRef$current3$s === void 0 || _imgInsRef$current3$s.call(_imgInsRef$current3, -0.1); + break; + case 'reset': + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current4 = imgInsRef.current) === null || _imgInsRef$current4 === void 0 || (_imgInsRef$current4$r = _imgInsRef$current4.reset) === null || _imgInsRef$current4$r === void 0 || _imgInsRef$current4$r.call(_imgInsRef$current4, -0.1); + break; + } + }; + + // ============================= cropper ========================= + // 手动截图相关参数 + var cropInsRef = useRef(null); + var _useState7 = useState(showOpt), + _useState8 = _slicedToArray(_useState7, 2), + showCrop = _useState8[0], + setShowCrop = _useState8[1]; + var _useState9 = useState(CROP_TYPE['AUTO']), + _useState10 = _slicedToArray(_useState9, 2), + cropType = _useState10[0], + setCropType = _useState10[1]; + + // 自动截图相关参数 + var _useState11 = useState([]), + _useState12 = _slicedToArray(_useState11, 2), + odList = _useState12[0], + setOdList = _useState12[1]; + var _useState13 = useState([]), + _useState14 = _slicedToArray(_useState13, 2), + extendOdList = _useState14[0], + setExtendOdList = _useState14[1]; + var _useState15 = useState(null), + _useState16 = _slicedToArray(_useState15, 2), + selectRectId = _useState16[0], + setSelectRectId = _useState16[1]; + + // 定位按钮相关参数 + var alginContainerRef = useRef(null); + var alignRef = useRef(null); + var _useState17 = useState(null), + _useState18 = _slicedToArray(_useState17, 2), + cropRect = _useState18[0], + setCropRect = _useState18[1]; + + // 选中的版本号 + var _useState19 = useState(null), + _useState20 = _slicedToArray(_useState19, 2), + selectAlgorithmVersion = _useState20[0], + setSelectAlgorithmVersion = _useState20[1]; + var handlerCropStartRef = useRef(null); + var handlerCropEndRef = useRef(null); + var handleShapeSelectRef = useRef(null); + useEffect(function () { + initData(dataSource[currentIndex].objects || objects); + return function () { + var _imgInsRef$current5, _imgInsRef$current5$c, _handlerCropStartRef$, _handlerCropEndRef$cu, _handleShapeSelectRef, _cropInsRef$current, _cropInsRef$current$d; + (_imgInsRef$current5 = imgInsRef.current) === null || _imgInsRef$current5 === void 0 || (_imgInsRef$current5$c = _imgInsRef$current5.clearShape) === null || _imgInsRef$current5$c === void 0 || _imgInsRef$current5$c.call(_imgInsRef$current5); + (_handlerCropStartRef$ = handlerCropStartRef.current) === null || _handlerCropStartRef$ === void 0 || _handlerCropStartRef$.remove(); + (_handlerCropEndRef$cu = handlerCropEndRef.current) === null || _handlerCropEndRef$cu === void 0 || _handlerCropEndRef$cu.remove(); + (_handleShapeSelectRef = handleShapeSelectRef.current) === null || _handleShapeSelectRef === void 0 || _handleShapeSelectRef.remove(); + cropInsRef === null || cropInsRef === void 0 || (_cropInsRef$current = cropInsRef.current) === null || _cropInsRef$current === void 0 || (_cropInsRef$current$d = _cropInsRef$current.destroy) === null || _cropInsRef$current$d === void 0 || _cropInsRef$current$d.call(_cropInsRef$current); + cropInsRef.current = null; + }; + }, [isImgReady, showCrop, cropType, currentIndex]); + var initData = function initData(_objects) { + var imgIns = imgInsRef.current; + var _odRect = dataSource[currentIndex].odRect; + //清理crop + setCropRect(null); + if (!isImgReady) return; + if (!showCrop) { + var _imgIns$addShape; + imgIns === null || imgIns === void 0 || (_imgIns$addShape = imgIns.addShape) === null || _imgIns$addShape === void 0 || _imgIns$addShape.call(imgIns, { + x: get(_odRect, 'x', 0), + y: get(_odRect, 'y', 0), + w: get(_odRect, 'w', 0), + h: get(_odRect, 'h', 0), + selectAble: false + }); + return; + } + + // 自动模式 + if (cropType === CROP_TYPE['AUTO']) { + var handleGetOD = function handleGetOD(odList) { + var imgSize = imgIns.getImgSize(); + var shapeList = odList.map(function (rect) { + return _objectSpread(_objectSpread({}, rect), {}, { + selectAble: true, + id: rect['id'], + algorithmVersion: rect.algorithmVersion + }); + }); + imgIns.replaceShape(shapeList); + //顺便吧扩展框拿到 + var extendRect = shapeList.map(function (rect) { + // @ts-ignore + var _extendRect = getExtendRect(rect, imgSize.w, imgSize.h, rect.algorithmVersion); + return _objectSpread(_objectSpread({}, rect), _extendRect); + }); + setExtendOdList(extendRect); + imgIns.replaceShape(shapeList); + handleShapeSelectRef.current = addEventListenerWrapper(imgContainerRef.current, 'shape-select', function (e) { + var id = e.detail; + setSelectRectId(id); + var selectShape = shapeList.find(function (v) { + return v['id'] === id; + }); + if (selectShape) { + setSelectAlgorithmVersion(selectShape['algorithmVersion']); + //换算成屏幕坐标 + var axisRect = imgIns.imgRectAxisToCanvasAxisRect(selectShape); + var _rect = { + x: axisRect.x2 > axisRect.x ? axisRect.x : axisRect.x2, + y: axisRect.y2 > axisRect.y ? axisRect.y : axisRect.y2, + w: Math.abs(axisRect.x2 - axisRect.x), + h: Math.abs(axisRect.y2 - axisRect.y) + }; + setCropRect(_rect); + } else { + // @ts-ignore + setCropRect(null); + } + }); + }; + // @ts-ignore + var rect = getOdRect({ + objects: _objects + }); + setOdList(rect); + handleGetOD(rect); + } + + // 手动模式 + if (cropType === CROP_TYPE['CUSTOM']) { + var _imgIns$clearShape; + // 手动框选状态预先清除imgIns + imgIns === null || imgIns === void 0 || (_imgIns$clearShape = imgIns.clearShape) === null || _imgIns$clearShape === void 0 || _imgIns$clearShape.call(imgIns); + handlerCropStartRef.current = addEventListenerWrapper(imgContainerRef.current, EVENT_CROP_START, function () { + setSelectAlgorithmVersion(null); + setCropRect(null); + }); + handlerCropEndRef.current = addEventListenerWrapper(imgContainerRef.current, EVENT_CROP_END, function (event) { + var _alignRef$current, _alignRef$current$for; + var data = event.detail; + setSelectAlgorithmVersion(null); + setCropRect({ + x: data.left, + y: data.top, + w: data.width, + h: data.height + }); + alignRef === null || alignRef === void 0 || (_alignRef$current = alignRef.current) === null || _alignRef$current === void 0 || (_alignRef$current$for = _alignRef$current.forceAlign) === null || _alignRef$current$for === void 0 || _alignRef$current$for.call(_alignRef$current); + }); + cropInsRef.current = new Cropper(imgContainerRef.current, { + showMask: true, + viewer: imgIns + }); + } + }; + + // 获取框选的截图框信息 + var latestCropType = useLatest(cropType); + var latestImgKey = useLatest(dataSource[currentIndex].imageKey); + var latestCropRect = useLatest(cropRect); + var getCropInfo = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var cropType, cropRect, imgIns, transform, newImgKey, rectList, extendRectList, selectIndex, shapes, shapeIds, newRect, data; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cropType = latestCropType.current; + cropRect = latestCropRect.current; + imgIns = imgInsRef.current; + transform = imgIns.targetTransform; + newImgKey = latestImgKey.current; + rectList = []; + extendRectList = []; + selectIndex = 0; + _context3.t0 = cropType; + _context3.next = _context3.t0 === CROP_TYPE['AUTO'] ? 11 : 17; + break; + case 11: + shapes = imgIns.getSelectShape(); + shapeIds = shapes.map(function (v) { + return v['id']; + }); + rectList = odList.filter(function (v) { + return shapeIds.includes(v['id']); + }).map(function (item) { + if (item.algorithmVersion === 'OBJECT_TYPE_FACE' || item.objectType === 'OBJECT_TYPE_FACE') { + if (!isNull(item.extendBox)) { + return _objectSpread(_objectSpread({}, item), {}, { + w: get(item, 'extendBox.w'), + h: get(item, 'extendBox.h'), + x: get(item, 'extendBox.x'), + y: get(item, 'extendBox.y') + }); + } + } else { + return item; + } + }); + extendRectList = extendOdList.filter(function (v) { + return shapeIds.includes(v['id']); + }).map(function (v) { + return pick(v, ['x', 'y', 'w', 'h', 'algorithmVersion', 'id']); + }); + selectIndex = rectList.findIndex(function (v) { + return v['id'] === selectRectId; + }); + return _context3.abrupt("break", 26); + case 17: + //获取旋转过的坐标 + // @ts-ignore + newRect = getTransformRect(imgIns.image, transform, cropRect); //判断是不是旋转过 + if (!(get(transform, 'rotate', 0) % 360 != 0)) { + _context3.next = 23; + break; + } + data = getRotateImg(imgIns.image, get(transform, 'rotate', 0)); //在画布上画旋转后的图片 + _context3.next = 22; + return upload(data); + case 22: + newImgKey = _context3.sent; + case 23: + rectList.push(newRect); + extendRectList.push(newRect); + return _context3.abrupt("break", 26); + case 26: + _context3.next = 28; + return Promise.all(extendRectList.map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(rect, index) { + var file, imgKey; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return getFileByRect(imgIns.image, rect); + case 2: + file = _context.sent; + _context.next = 5; + return upload(file); + case 5: + imgKey = _context.sent; + extendRectList[index] = _objectSpread(_objectSpread({}, rect), {}, { + imgKey: imgKey + }); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x, _x2) { + return _ref2.apply(this, arguments); + }; + }())); + case 28: + _context3.next = 30; + return Promise.all(rectList.map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(rect, index) { + var faceCorrectImage, faceCorrectImageKey, base64, blobData, file, newRect; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + faceCorrectImage = rect['faceCorrectImage']; + if (!faceCorrectImage) { + _context2.next = 8; + break; + } + base64 = "data:image/jpg;base64,".concat(faceCorrectImage); + blobData = dataURLToBlob(base64); + file = new window.File([blobData], "".concat(new Date().getTime())); + _context2.next = 7; + return upload(file); + case 7: + faceCorrectImageKey = _context2.sent; + case 8: + newRect = _objectSpread(_objectSpread({}, rect), faceCorrectImageKey ? { + faceCorrectImageKey: faceCorrectImageKey + } : {}); + delete newRect['faceCorrectImage']; + rectList[index] = newRect; + case 11: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x3, _x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 30: + return _context3.abrupt("return", { + rectList: rectList, + extendRectList: extendRectList, + selectIndex: selectIndex, + imgKey: newImgKey + }); + case 31: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function getCropInfo() { + return _ref.apply(this, arguments); + }; + }(); + + // 操作界面判断 + var handleCropBtnClick = function handleCropBtnClick(v) { + switch (v) { + case 'close': + setShowCrop(false); + break; + case 'autoCrop': + setCropType(CROP_TYPE['AUTO']); + break; + case 'customCrop': + setCropType(CROP_TYPE['CUSTOM']); + break; + } + }; + + // ============================= attact img ========================= + var _useState21 = useState(0), + _useState22 = _slicedToArray(_useState21, 2), + selectAttachImgIndex = _useState22[0], + setSelectAttachImgIndex = _useState22[1]; + var _useState23 = useState(false), + _useState24 = _slicedToArray(_useState23, 2), + isZoomin = _useState24[0], + setIsZoomin = _useState24[1]; + + /** + * 修改当前图片预览下标 + * @param diff 跳转强度 正向后翻、负值向前翻 + */ + var handleChangeIndex = function handleChangeIndex(diff) { + var _dataSource$_index; + var _index = currentIndex + diff; + if (!(dataSource !== null && dataSource !== void 0 && (_dataSource$_index = dataSource[_index]) !== null && _dataSource$_index !== void 0 && _dataSource$_index.imageKey)) return; + setCurrentIndex(_index); + }; + + // ============================== Ref =============================== + useImperativeHandle(ref, function () { + return { + imgInsRef: imgInsRef, + setShowCrop: setShowCrop, + initData: initData, + getCropInfo: getCropInfo, + handleChangeIndex: handleChangeIndex + }; + }); + return /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName)), + style: { + height: height, + width: width + } + }, dataSource.length ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "-main"), cropType === CROP_TYPE['AUTO'] && "".concat(componentName, "-main--cursor")), + ref: init + }), !hideLeftTopBtn && /*#__PURE__*/React.createElement(BtnGroup, { + className: classNames("".concat(componentName, "-opt")), + dataSource: operateBtnDataSource, + onClick: handleOptClick, + placement: "left" + }), showCrop && /*#__PURE__*/React.createElement(BtnGroup, { + circle: true, + className: classNames("".concat(componentName, "-crop-opt")), + dataSource: cropBtnDataSource, + onClick: handleCropBtnClick, + selectKey: cropType === CROP_TYPE['AUTO'] ? 'autoCrop' : 'customCrop' + }), showCrop && cropRect && screenshotButtonRender && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { + ref: alginContainerRef, + className: classNames("".concat(componentName, "-align")), + style: Object.assign({ + width: cropRect.w, + height: cropRect.h + }, getTransforms({ + translateX: cropRect.x, + translateY: cropRect.y + })) + }), /*#__PURE__*/React.createElement(Align, { + ref: alignRef, + monitorWindowResize: true, + align: screenshotButtonAlign, + target: function target() { + return alginContainerRef.current; + } + }, screenshotButtonRender({ + model: 'IMAGE', + getCropInfo: getCropInfo, + setShowCrop: setShowCrop, + cropType: cropType, + selectAlgorithmVersion: selectAlgorithmVersion + }))), ((_dataSource$currentIn2 = dataSource[currentIndex].attachImg) === null || _dataSource$currentIn2 === void 0 ? void 0 : _dataSource$currentIn2.length) && !showCrop && /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "-attach"), isZoomin && "".concat(componentName, "-attach--zoomin"), "".concat(componentName, "-attach--fixed"), isZoomin && "".concat(componentName, "-attach--zoomin--fixed")) + }, /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "-attach__tab")) + }, showAttachImgLabel ? (_dataSource$currentIn3 = dataSource[currentIndex].attachImg) === null || _dataSource$currentIn3 === void 0 ? void 0 : _dataSource$currentIn3.map(function (_ref4, index) { + var label = _ref4.label; + return /*#__PURE__*/React.createElement("div", { + key: index, + className: classNames("".concat(componentName, "-attach__tab-item"), selectAttachImgIndex === index && "".concat(componentName, "-attach__tab-item--select")), + onMouseEnter: function onMouseEnter() { + setSelectAttachImgIndex(index); + } + }, label); + }) : null), /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "-attach__scale")) + }, /*#__PURE__*/React.createElement(Button, { + type: "text" + //绝对定位下onClick事件失效采用onMouseDown + , + onMouseDown: function onMouseDown(e) { + //如果是左键执行 + if (e.button == 0) { + setIsZoomin(function (pre) { + return !pre; + }); + } + }, + style: { + color: '#fff' + } + }, /*#__PURE__*/React.createElement(Icon, { + styles: { + display: 'flex' + }, + icon: isZoomin ? 'icon-cancle_fullscreen' : 'icon-fullscreen' + }))), /*#__PURE__*/React.createElement("img", { + draggable: "false", + className: classNames("".concat(componentName, "-attach__img"), "".concat(componentName, "-attach__img--fixed")), + src: get(dataSource[currentIndex].attachImg, "".concat(selectAttachImgIndex, ".url"), '') + })), showScore && /*#__PURE__*/React.createElement("div", { + style: { + bottom: 20 + }, + className: classNames("".concat(componentName, "__face-score")) + }, "\u4EBA\u8138\u8D28\u91CF\u5206\uFF1A".concat(Number(dataSource[currentIndex].score).toFixed(2)))) : /*#__PURE__*/React.createElement(Empty, { + image: Empty.PRESENTED_IMAGE_SIMPLE, + description: "\u6682\u65E0\u6570\u636E" + })); +}); +BigImagePreview.displayName = 'BigImagePreview'; +export default BigImagePreview; \ No newline at end of file diff --git a/packages/hooks/lib/useIMEComposition/constants.d.ts b/packages/meta/es/BigImagePreview/bigImagePreviewHelper.d.ts similarity index 100% rename from packages/hooks/lib/useIMEComposition/constants.d.ts rename to packages/meta/es/BigImagePreview/bigImagePreviewHelper.d.ts diff --git a/packages/hooks/lib/useIMEComposition/constants.js b/packages/meta/es/BigImagePreview/bigImagePreviewHelper.js similarity index 100% rename from packages/hooks/lib/useIMEComposition/constants.js rename to packages/meta/es/BigImagePreview/bigImagePreviewHelper.js diff --git a/packages/meta/es/BigImagePreview/components/BtnGroup/index.d.ts b/packages/meta/es/BigImagePreview/components/BtnGroup/index.d.ts new file mode 100644 index 0000000..960a037 --- /dev/null +++ b/packages/meta/es/BigImagePreview/components/BtnGroup/index.d.ts @@ -0,0 +1,17 @@ +import React, { MouseEvent } from 'react'; +import { TooltipProps } from 'antd'; +import './index.less'; +export interface BtnGroupProps { + className: string; + dataSource: Array<{ + key: string; + icon: string; + title: string; + }>; + onClick: (v: string, e: MouseEvent) => void; + selectKey?: string; + circle?: boolean; + placement?: TooltipProps['placement']; +} +export declare const BtnGroup: React.FC; +export default BtnGroup; diff --git a/packages/meta/es/BigImagePreview/components/BtnGroup/index.js b/packages/meta/es/BigImagePreview/components/BtnGroup/index.js new file mode 100644 index 0000000..52e621c --- /dev/null +++ b/packages/meta/es/BigImagePreview/components/BtnGroup/index.js @@ -0,0 +1,42 @@ +import React from 'react'; +import classNames from 'classnames'; +import { Button, Tooltip } from 'antd'; +import Icon from "../../../iconfont"; +import "./index.less"; +var componentName = "zhst-image__btn-group"; +export var BtnGroup = function BtnGroup(props) { + var dataSource = props.dataSource, + _onClick = props.onClick, + className = props.className, + circle = props.circle, + _props$selectKey = props.selectKey, + selectKey = _props$selectKey === void 0 ? '' : _props$selectKey, + _props$placement = props.placement, + placement = _props$placement === void 0 ? 'right' : _props$placement; + return /*#__PURE__*/React.createElement("div", { + className: classNames(componentName, circle && "".concat(componentName, "--circle"), className) + }, dataSource.map(function (_ref) { + var key = _ref.key, + icon = _ref.icon, + title = _ref.title; + var isSelect = key === selectKey; + return /*#__PURE__*/React.createElement(Tooltip, { + key: key, + placement: placement, + title: title + }, /*#__PURE__*/React.createElement("div", { + key: key, + className: classNames("".concat(componentName, "__item"), isSelect && "".concat(componentName, "__item--active")) + }, /*#__PURE__*/React.createElement(Button, { + type: "text", + onClick: function onClick(e) { + _onClick(key, e); + } + }, /*#__PURE__*/React.createElement(Icon, { + size: 18, + icon: icon + })))); + })); +}; +BtnGroup.displayName = 'BtnGroup'; +export default BtnGroup; \ No newline at end of file diff --git a/packages/meta/es/BigImagePreview/components/BtnGroup/index.less b/packages/meta/es/BigImagePreview/components/BtnGroup/index.less new file mode 100644 index 0000000..db03187 --- /dev/null +++ b/packages/meta/es/BigImagePreview/components/BtnGroup/index.less @@ -0,0 +1,51 @@ +.zhst-image__btn-group { + // display: flex; + width: 30px; + box-shadow: 0 2px 6px 0 rgb(0 0 0 / 40%); + + &__item { + display: flex; + width: 30px; + height: 30px; + align-items: center; + justify-content: center; + background: #000; + + &>button { + padding: 0; + color: #fff; + + &:hover { + color: #09f; + } + + &:active { + color: #09f; + } + + &:focus { + color: #fff; + } + + &>span { + display: flex; + } + } + + &--active { + &>button { + color: #09f; + } + } + } + + &--circle { + background-color: none; + box-shadow: none; + } + + &--circle &__item { + margin-bottom: 4px; + border-radius: 50%; + } +} diff --git a/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.d.ts b/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.d.ts new file mode 100644 index 0000000..cb09279 --- /dev/null +++ b/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.d.ts @@ -0,0 +1,14 @@ +import React from 'react'; +import type { AlgorithmVersion } from '@zhst/types'; +import './index.less'; +interface IScreenShotButton { + getCropInfo: () => void; + setShowCrop: any; + cropType: string; + selectAlgorithmVersion?: AlgorithmVersion | null; +} +declare const getScreenshotButtonRender: (arg: { + disableBtn: number[]; + onBigImageActionClick: (type: number, item: any) => void; +}) => (param: IScreenShotButton) => React.JSX.Element; +export default getScreenshotButtonRender; diff --git a/packages/biz/es/utils/request.js b/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.js similarity index 53% rename from packages/biz/es/utils/request.js rename to packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.js index 9eb1054..64121a6 100644 --- a/packages/biz/es/utils/request.js +++ b/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.js @@ -2,120 +2,123 @@ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { return typeof fn === "function"; } } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -import { extend } from 'umi-request'; -import { get } from '@zhst/func'; -import { message } from 'antd'; -import base64 from 'base-64'; -export var ResponseError = /*#__PURE__*/function (_Error) { - _inherits(ResponseError, _Error); - var _super = _createSuper(ResponseError); - function ResponseError(response, text, data, request) { - var _this; - var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'ResponseError'; - _classCallCheck(this, ResponseError); - _this = _super.call(this, text || response.statusText); - _defineProperty(_assertThisInitialized(_this), "name", void 0); - _defineProperty(_assertThisInitialized(_this), "data", void 0); - _defineProperty(_assertThisInitialized(_this), "response", void 0); - _defineProperty(_assertThisInitialized(_this), "request", void 0); - _defineProperty(_assertThisInitialized(_this), "type", void 0); - _this.name = 'ResponseError'; - _this.data = data; - _this.response = response; - _this.request = request; - _this.type = type; - return _this; - } - return _createClass(ResponseError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); -export var request = extend({ - getResponse: true, - // timeout: 1000, - parseResponse: false -}); - -//错误处理中间件 -request.use( /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(ctx, next) { - var req, _ref2, _ref2$toast, toast, res, d, isEmptyRes, body, errMsg, _window$utf; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - req = ctx.req; - _ref2 = (req === null || req === void 0 ? void 0 : req.options) || {}, _ref2$toast = _ref2.toast, toast = _ref2$toast === void 0 ? true : _ref2$toast; - _context.prev = 2; - _context.next = 5; - return next(); - case 5: - res = ctx.res; - _context.next = 8; - return res.text(); - case 8: - d = _context.sent; - if (!(res.status === 401)) { - _context.next = 12; - break; - } - message.warning('登录过期,请重新登录!'); - return _context.abrupt("return"); - case 12: - isEmptyRes = d === ''; //有些后端接口成功会返回空 做下兼容 - body = !isEmptyRes ? JSON.parse(d) : d; - if (!(res.status >= 200 && res.status < 300)) { - _context.next = 18; - break; - } - ctx.res = body; - _context.next = 22; - break; - case 18: - // 先判断Grpc-Metadata-Errorx-Message - errMsg = res.headers.get('Grpc-Metadata-Errorx-Message'); - if (errMsg) { - errMsg = (_window$utf = window.utf8) === null || _window$utf === void 0 ? void 0 : _window$utf.decode(base64.decode(errMsg)); - // 后判断 body中的message - } else if (!errMsg && get(body, 'message')) { - errMsg = "".concat(get(body, 'message')); - } else { - // 最后看状态码 - errMsg = '您的网络发生异常,无法连接服务器'; - } - toast && message.error(errMsg); - throw new ResponseError(res, errMsg, d, req, 'CustomError'); - case 22: - _context.next = 28; - break; - case 24: - _context.prev = 24; - _context.t0 = _context["catch"](2); - if (get(_context.t0, 'type') !== 'CustomError') { - toast && message.error('您的网络发生异常,无法连接服务器'); - } - throw _context.t0; - case 28: - case "end": - return _context.stop(); +import React from 'react'; +import { Button } from 'antd'; +import classNames from 'classnames'; +import { IBigImageOpt } from '@zhst/types/BigImageModal'; +import "./index.less"; +var componentName = 'bigImageWrapper--v2'; +var getScreenshotButtonRender = function getScreenshotButtonRender(arg) { + var _arg$disableBtn = arg.disableBtn, + disableBtn = _arg$disableBtn === void 0 ? [] : _arg$disableBtn, + onBigImageActionClick = arg.onBigImageActionClick; + return function (param) { + var getCropInfo = param.getCropInfo, + setShowCrop = param.setShowCrop, + cropType = param.cropType, + selectAlgorithmVersion = param.selectAlgorithmVersion; + var isAuto = cropType === 'AUTO'; + return /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "__screenshot")), + style: { + zIndex: 100, + position: 'absolute', + width: '86px' } - }, _callee, null, [[2, 24]]); - })); - return function (_x, _x2) { - return _ref.apply(this, arguments); + }, !disableBtn.includes(IBigImageOpt['ADD_HISTORY_WITH_CROP']) && isAuto && /*#__PURE__*/React.createElement(Button, { + type: 'text', + onClick: /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(e) { + var image; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + e.stopPropagation(); + _context.next = 3; + return getCropInfo(); + case 3: + image = _context.sent; + setShowCrop(false); + onBigImageActionClick(IBigImageOpt['ADD_HISTORY_WITH_CROP'], image); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }() + }, "\u76EE\u6807\u68C0\u7D22"), !disableBtn.includes(IBigImageOpt['ADD_HISTORY_WITH_CROP_BODY']) && !isAuto && /*#__PURE__*/React.createElement(Button, { + type: 'text', + onClick: /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) { + var image; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + e.stopPropagation(); + _context2.next = 3; + return getCropInfo(); + case 3: + image = _context2.sent; + setShowCrop(false); + onBigImageActionClick(IBigImageOpt['ADD_HISTORY_WITH_CROP_BODY'], image); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x2) { + return _ref2.apply(this, arguments); + }; + }() + }, "\u641C\u5F62\u4F53"), !disableBtn.includes(IBigImageOpt['ADD_HISTORY_WITH_CROP_VEHICLE']) && !isAuto && /*#__PURE__*/React.createElement(Button, { + type: 'text', + onClick: /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(e) { + var image; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + e.stopPropagation(); + _context3.next = 3; + return getCropInfo(); + case 3: + image = _context3.sent; + setShowCrop(false); + onBigImageActionClick(IBigImageOpt['ADD_HISTORY_WITH_CROP_VEHICLE'], image); + case 6: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x3) { + return _ref3.apply(this, arguments); + }; + }() + }, "\u641C\u975E\u673A\u52A8\u8F66"), !disableBtn.includes(IBigImageOpt['ADD_HISTORY_WITH_CROP_ARCHIVE']) && selectAlgorithmVersion !== 0 && /*#__PURE__*/React.createElement(Button, { + type: 'text', + onClick: function onClick(e) { + e.stopPropagation(); + var image = getCropInfo(); + setShowCrop(false); + if (!image.rectList[0].algorithmVersion) { + image.rectList[0].algorithmVersion = 0; + image.extendRectList[0].algorithmVersion = 0; + } + onBigImageActionClick(IBigImageOpt['ADD_HISTORY_WITH_CROP_ARCHIVE'], image); + } + }, "\u6863\u6848\u68C0\u7D22"), /*#__PURE__*/React.createElement(Button, { + type: 'text', + onClick: function onClick(e) { + e.stopPropagation(); + setShowCrop(false); + } + }, "\u9000\u51FA\u6846\u9009")); }; -}()); -export default request; \ No newline at end of file +}; +export default getScreenshotButtonRender; \ No newline at end of file diff --git a/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.less b/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.less new file mode 100644 index 0000000..ca407fa --- /dev/null +++ b/packages/meta/es/BigImagePreview/components/ScreenhotButtons/index.less @@ -0,0 +1,21 @@ +.bigImageWrapper--v2__screenshot { + min-width: 90px; + background: rgb(0 0 0 / 50%); + border-radius: 0; + + &>button { + width: 100%; + color: #fff !important; + font-family: 'Microsoft YaHei'; + font-size: 12px !important; + border-radius: 0; + + &>span { + color: #fff; + } + + &:hover { + background-color: #09f !important; + } + } +} diff --git a/packages/meta/es/BigImagePreview/index.d.ts b/packages/meta/es/BigImagePreview/index.d.ts new file mode 100644 index 0000000..7469634 --- /dev/null +++ b/packages/meta/es/BigImagePreview/index.d.ts @@ -0,0 +1,3 @@ +import BigImagePreview from './BigImagePreview'; +export type { ImgViewProps } from './BigImagePreview'; +export default BigImagePreview; diff --git a/packages/meta/es/BigImagePreview/index.js b/packages/meta/es/BigImagePreview/index.js new file mode 100644 index 0000000..abc99c3 --- /dev/null +++ b/packages/meta/es/BigImagePreview/index.js @@ -0,0 +1,2 @@ +import BigImagePreview from "./BigImagePreview"; +export default BigImagePreview; \ No newline at end of file diff --git a/packages/meta/es/BigImagePreview/index.less b/packages/meta/es/BigImagePreview/index.less new file mode 100644 index 0000000..d192880 --- /dev/null +++ b/packages/meta/es/BigImagePreview/index.less @@ -0,0 +1,123 @@ +.zhst-image__img-view { + position: relative; + width: calc(100%); + height: 100%; + + &__face-score { + position: absolute; + right: 20px; + bottom: 80px; + color: red; + font-family: 'Microsoft YaHei'; + font-size: 19px; + font-weight: bold; + } + + &-opt { + position: absolute; + z-index: 99; + top: 0; + } + + &-crop-opt { + position: absolute; + z-index: 99; + top: 0; + right: 0; + } + + &-align { + position: absolute; + top: 0; + left: 0; + pointer-events: none; + } + + &-main { + width: 100%; + height: 100%; + font-size: 0; + + &--cursor { + & canvas { + min-height: 320px; + cursor: pointer; + } + } + } + + &-screenshot { + position: absolute; + z-index: 10; + } + + &-attach { + position: absolute; + z-index: 11; + bottom: 0; + + // left: 78px; + left: 0; + min-width: 120px; + height: 202px; + transition: all 200ms; + + &--zoomin { + height: 100%; + } + + &__tab { + position: absolute; + top: 0; + left: 0; + display: flex; + + &-item { + display: flex; + width: 30px; + height: 24px; + align-items: center; + justify-content: center; + background: #000; + color: #fff; + cursor: pointer; + font-size: 12px; + opacity: 0.5; + transition: all 200ms; + + &--select { + width: 48px; + height: 34px; + background: #09f; + opacity: 1; + } + } + } + + &__scale { + position: absolute; + top: 4px; + right: 4px; + display: flex; + width: 30px; + height: 30px; + align-items: center; + justify-content: center; + background: rgb(0 0 0 / 60%); + border-radius: 100%; + cursor: pointer; + line-height: 30px; + text-align: center; + } + + &__img { + height: 100%; + object-fit: contain; + + &--fixed { + width: 100%; + object-fit: contain; + } + } + } +} diff --git a/packages/meta/es/CompareImage/CompareImage.d.ts b/packages/meta/es/CompareImage/CompareImage.d.ts new file mode 100644 index 0000000..18fbaca --- /dev/null +++ b/packages/meta/es/CompareImage/CompareImage.d.ts @@ -0,0 +1,20 @@ +import React from 'react'; +import './index.less'; +export interface CompareImageProps { + /** + * @description 属性描述 + * @default "默认值" + */ + label: string; + openRoll?: boolean; + dataSource?: Array<{ + url: string; + score: number; + }>; + showScore?: boolean; + current: number; +} +export interface CompareImageRefProps { +} +declare const CompareImage: React.ForwardRefExoticComponent>; +export default CompareImage; diff --git a/packages/meta/es/ImagePreview/index.js b/packages/meta/es/CompareImage/CompareImage.js similarity index 72% rename from packages/meta/es/ImagePreview/index.js rename to packages/meta/es/CompareImage/CompareImage.js index 6bc9061..290df60 100644 --- a/packages/meta/es/ImagePreview/index.js +++ b/packages/meta/es/CompareImage/CompareImage.js @@ -4,24 +4,27 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o = function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -import React, { useRef, useState, useEffect, useCallback } from 'react'; -import { generateImg, get, addEventListener } from '@zhst/func'; +import React, { useRef, useState, useEffect, forwardRef, useImperativeHandle } from 'react'; +import { generateImg, get, addEventListenerWrapper } from '@zhst/func'; import { useUpdateEffect } from '@zhst/hooks'; import { Button } from 'antd'; import classNames from 'classnames'; import Viewer from "../ImageEditor/viewer"; import Icon from "../iconfont"; import CornerScore from "./components/CornerScore"; +import "./index.less"; var componentName = "zhst-image__compater-view"; // 对比图组件 -var CompaterImage = function CompaterImage(props) { - var url = props.url, - label = props.label, +var CompareImage = /*#__PURE__*/forwardRef(function (props, ref) { + var label = props.label, _props$openRoll = props.openRoll, openRoll = _props$openRoll === void 0 ? false : _props$openRoll, - _props$urls = props.urls, - urls = _props$urls === void 0 ? [] : _props$urls, - score = props.score; + _props$dataSource = props.dataSource, + dataSource = _props$dataSource === void 0 ? [] : _props$dataSource, + _props$showScore = props.showScore, + showScore = _props$showScore === void 0 ? true : _props$showScore, + _props$current = props.current, + current = _props$current === void 0 ? 0 : _props$current; var imgContainerRef = useRef(null); var imgInsRef = useRef(null); var _useState = useState(0), @@ -29,65 +32,56 @@ var CompaterImage = function CompaterImage(props) { scale = _useState2[0], setScale = _useState2[1]; //图片翻页机制 - var _useState3 = useState(generateImg(url)), + var _useState3 = useState(current), _useState4 = _slicedToArray(_useState3, 2), - showUrl = _useState4[0], - setShowUrl = _useState4[1]; //记录显示的图片 + currentIndex = _useState4[0], + setCurrentIndex = _useState4[1]; - useUpdateEffect(function () { - setShowUrl(generateImg(url)); - if (imgInsRef.current) { - var _imgInsRef$current; - (_imgInsRef$current = imgInsRef.current) === null || _imgInsRef$current === void 0 || _imgInsRef$current.refleshImage({ - image: generateImg(url) - }); - } - }, [url]); + // 初始化页面 useEffect(function () { - setShowUrl(url); - var handleTransformChange = addEventListener(imgContainerRef.current, 'viewer-transform-change', function (event) { + var handleTransformChange = addEventListenerWrapper(imgContainerRef.current, 'viewer-transform-change', function (event) { var data = event.detail; setScale(get(data, 'scale', 0)); }); - imgInsRef.current = new Viewer(imgContainerRef.current, { - image: generateImg(url) - }); + if (generateImg(dataSource[currentIndex].url)) { + imgInsRef.current = new Viewer(imgContainerRef.current, { + image: generateImg(dataSource[currentIndex].url) + }); + } return function () { - var _imgInsRef$current2, _imgInsRef$current2$d; + var _imgInsRef$current, _imgInsRef$current$de; handleTransformChange === null || handleTransformChange === void 0 || handleTransformChange.remove(); - imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current2 = imgInsRef.current) === null || _imgInsRef$current2 === void 0 || (_imgInsRef$current2$d = _imgInsRef$current2.destroy) === null || _imgInsRef$current2$d === void 0 || _imgInsRef$current2$d.call(_imgInsRef$current2); + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current = imgInsRef.current) === null || _imgInsRef$current === void 0 || (_imgInsRef$current$de = _imgInsRef$current.destroy) === null || _imgInsRef$current$de === void 0 || _imgInsRef$current$de.call(_imgInsRef$current); imgInsRef.current = null; }; }, []); - //向前翻页 - var handlePre = useCallback(function () { - var index = urls.findIndex(function (v) { - return v === showUrl; - }); - if (index > 0) { - var _imgInsRef$current3; - var newUrl = urls[index - 1]; - setShowUrl(newUrl); - (_imgInsRef$current3 = imgInsRef.current) === null || _imgInsRef$current3 === void 0 || _imgInsRef$current3.refleshImage({ - image: newUrl + // 监听下标变化 + useUpdateEffect(function () { + if (imgInsRef.current) { + var _imgInsRef$current2; + (_imgInsRef$current2 = imgInsRef.current) === null || _imgInsRef$current2 === void 0 || _imgInsRef$current2.refleshImage({ + image: generateImg(dataSource[currentIndex].url) }); } - }, [showUrl, urls]); - //向后翻页 - var handleNext = useCallback(function () { - var index = urls.findIndex(function (v) { - return v === showUrl; + }, [currentIndex]); + + // 翻页实践 + var handleIndexChange = function handleIndexChange(changeVal) { + var _dataSource$_index, _imgInsRef$current3; + var _index = currentIndex + changeVal; + if (!(dataSource !== null && dataSource !== void 0 && (_dataSource$_index = dataSource[_index]) !== null && _dataSource$_index !== void 0 && _dataSource$_index.url)) return; + (_imgInsRef$current3 = imgInsRef.current) === null || _imgInsRef$current3 === void 0 || _imgInsRef$current3.refleshImage({ + image: generateImg(dataSource[_index].url) }); - if (index >= 0 && !!urls[index + 1]) { - var _imgInsRef$current4; - var newUrl = urls[index + 1]; - setShowUrl(newUrl); - (_imgInsRef$current4 = imgInsRef.current) === null || _imgInsRef$current4 === void 0 || _imgInsRef$current4.refleshImage({ - image: newUrl - }); - } - }, [showUrl, urls]); + setCurrentIndex(_index); + }; + useImperativeHandle(ref, function () { + return { + imgInsRef: imgInsRef, + handleIndexChange: handleIndexChange + }; + }); return /*#__PURE__*/React.createElement("div", { className: classNames("".concat(componentName, "__container")) }, /*#__PURE__*/React.createElement("div", { @@ -95,23 +89,21 @@ var CompaterImage = function CompaterImage(props) { }, label), /*#__PURE__*/React.createElement("div", { ref: imgContainerRef, className: classNames("".concat(componentName, "__view")) - }), !url && /*#__PURE__*/React.createElement("div", { + }), !dataSource.length && /*#__PURE__*/React.createElement("div", { className: classNames("".concat(componentName, "__empty")) }, /*#__PURE__*/React.createElement("img", { src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANkupk+ACNPvkSPcAAEibACyXUyfABGm3yNHuAECRNgAZLuYPgEirKlHu7u7XdyytGwHAd8jjNyng4OD7vnz51dbPT8/7z58+NB9+/bt6jU/TI+AGWHEnrx48eJ/EsSmHzx40L18+fLyzxF3ZVMjEyDCiEDjMYZZS5wiPXnyZFbJaxMhQIQRGzHvWR7XCyOCXsOmiDAi1HmPMMQjDpbpEiDCiL358eNHurW/5SnWdIBbXiDCiA38/Pnzrce2YyZ4//59F3ePLNMl4PbpiL2J0L979+7yDtHDhw8vtzzvdGnEXdvUigSIsCLAWavHp/+qM0BcXMd/q25n1vF57TYBp0a3mUzilePj4+7k5KSLb6gt6ydAhPUzXnoPR0dHl79WGTNCfBnn1uvSCJdegQhLI1vvCk+fPu2ePXt2tZOYEV6/fn31dz+shwAR1sP1cqvLntbEN9MxA9xcYjsxS1jWR4AIa2Ibzx0tc44fYX/16lV6NDFLXH+YL32jwiACRBiEbf5KcXoTIsQSpzXx4N28Ja4BQoK7rgXiydbHjx/P25TaQAJEGAguWy0+2Q8PD6/Ki4R8EVl+bzBOnZY95fq9rj9zAkTI2SxdidBHqG9+skdw43borCXO/ZcJdraPWdv22uIEiLA4q7nvvCug8WTqzQveOH26fodo7g6uFe/a17W3+nFBAkRYENRdb1vkkz1CH9cPsVy/jrhr27PqMYvENYNlHAIesRiBYwRy0V+8iXP8+/fvX11Mr7L7ECueb/r48eMqm7FuI2BGWDEG8cm+7G3NEOfmdcTQw4h9/55lhm7DekRYKQPZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==", title: "\u6682\u65E0\u6570\u636E" }), /*#__PURE__*/React.createElement("span", { className: classNames("".concat(componentName, "__empty--text")) - }, "\u6682\u65E0\u5339\u914D\u6570\u636E")), !!url && openRoll && /*#__PURE__*/React.createElement("div", { + }, "\u6682\u65E0\u5339\u914D\u6570\u636E")), !!dataSource.length && openRoll && /*#__PURE__*/React.createElement("div", { className: classNames("".concat(componentName, "__scoll-module")) }, /*#__PURE__*/React.createElement(Button, { type: 'default', className: classNames("".concat(componentName, "__scoll-module__btn")), - disabled: !urls[urls.findIndex(function (v) { - return v === showUrl; - }) - 1], + disabled: currentIndex <= 0, onClick: function onClick() { - handlePre(); + handleIndexChange(-1); } }, /*#__PURE__*/React.createElement(Icon, { icon: "icon-qiehuanzuo", @@ -119,24 +111,22 @@ var CompaterImage = function CompaterImage(props) { })), /*#__PURE__*/React.createElement(Button, { type: 'default', className: classNames("".concat(componentName, "__scoll-module__btn")), - disabled: !urls[urls.findIndex(function (v) { - return v === showUrl; - }) + 1], + disabled: currentIndex >= dataSource.length - 1, onClick: function onClick() { - handleNext(); + handleIndexChange(1); } }, /*#__PURE__*/React.createElement(Icon, { icon: "icon-qiehuanyou", size: 40 - }))), !!score && /*#__PURE__*/React.createElement(CornerScore, { - scoreTxt: score + }))), showScore && /*#__PURE__*/React.createElement(CornerScore, { + scoreTxt: dataSource[currentIndex].score }), /*#__PURE__*/React.createElement("div", { className: classNames("".concat(componentName, "__tool")) }, /*#__PURE__*/React.createElement(Button, { type: "text", onClick: function onClick() { - var _imgInsRef$current5, _imgInsRef$current5$s; - imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current5 = imgInsRef.current) === null || _imgInsRef$current5 === void 0 || (_imgInsRef$current5$s = _imgInsRef$current5.scaleTo) === null || _imgInsRef$current5$s === void 0 || _imgInsRef$current5$s.call(_imgInsRef$current5, 0.1); + var _imgInsRef$current4, _imgInsRef$current4$s; + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current4 = imgInsRef.current) === null || _imgInsRef$current4 === void 0 || (_imgInsRef$current4$s = _imgInsRef$current4.scaleTo) === null || _imgInsRef$current4$s === void 0 || _imgInsRef$current4$s.call(_imgInsRef$current4, 0.1); } }, /*#__PURE__*/React.createElement(Icon, { size: 16, @@ -144,8 +134,8 @@ var CompaterImage = function CompaterImage(props) { }), /*#__PURE__*/React.createElement("span", null, '放大')), /*#__PURE__*/React.createElement(Button, { type: "text", onClick: function onClick() { - var _imgInsRef$current6, _imgInsRef$current6$s; - imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current6 = imgInsRef.current) === null || _imgInsRef$current6 === void 0 || (_imgInsRef$current6$s = _imgInsRef$current6.scaleTo) === null || _imgInsRef$current6$s === void 0 || _imgInsRef$current6$s.call(_imgInsRef$current6, -0.1); + var _imgInsRef$current5, _imgInsRef$current5$s; + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current5 = imgInsRef.current) === null || _imgInsRef$current5 === void 0 || (_imgInsRef$current5$s = _imgInsRef$current5.scaleTo) === null || _imgInsRef$current5$s === void 0 || _imgInsRef$current5$s.call(_imgInsRef$current5, -0.1); } }, /*#__PURE__*/React.createElement(Icon, { size: 16, @@ -157,12 +147,12 @@ var CompaterImage = function CompaterImage(props) { }), /*#__PURE__*/React.createElement(Button, { type: "text", onClick: function onClick() { - var _imgInsRef$current7, _imgInsRef$current7$r; - imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current7 = imgInsRef.current) === null || _imgInsRef$current7 === void 0 || (_imgInsRef$current7$r = _imgInsRef$current7.reset) === null || _imgInsRef$current7$r === void 0 || _imgInsRef$current7$r.call(_imgInsRef$current7); + var _imgInsRef$current6, _imgInsRef$current6$r; + imgInsRef === null || imgInsRef === void 0 || (_imgInsRef$current6 = imgInsRef.current) === null || _imgInsRef$current6 === void 0 || (_imgInsRef$current6$r = _imgInsRef$current6.reset) === null || _imgInsRef$current6$r === void 0 || _imgInsRef$current6$r.call(_imgInsRef$current6); } }, /*#__PURE__*/React.createElement(Icon, { size: 16, icon: 'icon-zhongzhi3' }), /*#__PURE__*/React.createElement("span", null, '重置')))); -}; -export default CompaterImage; \ No newline at end of file +}); +export default CompareImage; \ No newline at end of file diff --git a/packages/meta/es/ImagePreview/components/CornerScore/index.d.ts b/packages/meta/es/CompareImage/components/CornerScore/index.d.ts similarity index 100% rename from packages/meta/es/ImagePreview/components/CornerScore/index.d.ts rename to packages/meta/es/CompareImage/components/CornerScore/index.d.ts diff --git a/packages/meta/es/ImagePreview/components/CornerScore/index.js b/packages/meta/es/CompareImage/components/CornerScore/index.js similarity index 100% rename from packages/meta/es/ImagePreview/components/CornerScore/index.js rename to packages/meta/es/CompareImage/components/CornerScore/index.js diff --git a/packages/meta/src/ImagePreview/components/CornerScore/index.less b/packages/meta/es/CompareImage/components/CornerScore/index.less similarity index 94% rename from packages/meta/src/ImagePreview/components/CornerScore/index.less rename to packages/meta/es/CompareImage/components/CornerScore/index.less index 432e1b2..cb8bf35 100644 --- a/packages/meta/src/ImagePreview/components/CornerScore/index.less +++ b/packages/meta/es/CompareImage/components/CornerScore/index.less @@ -6,7 +6,6 @@ height: 22px; line-height: 22px; text-align: right; - vertical-align: bottom; padding-right: 1px; background-size: 100%; background-image: url('data: image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAAAsCAYAAAC9rDzHAAAByUlEQVR4Xu2cO08DMRCEJy0tlNBCSwmU0EIJLbS0UEILLTX/Fo3kk1AUHrrsjB3dWIoUnZTdvfnOZ6+1mxXGGHsADgEcA9hvnyMAvJ7xiwKrjuoQ0HmDxu8ZMxToAZDQrgAE2gxg6z9xAjwFcAvgoCDumGgKuADeA7iI6vUKqAFyE/KU12U9uMmiGuBr4Ong0bIS4A2Aa234sa4CyFzuPfLqFVABfGg5nv4OFu5BAZAbl4+F62q7fQVAJul3tjtYuCMFwEcATNozDAooAL7ltMVATngS8+kLP54UMzAAjc9VABrFVrgKQIWqRpsBaBRb4SoAFaoabQagUWyFqwBUqGq0GYBGsRWuAlChqtFmABrFVrgKQIWqRpsBaBRb4SoAFaoabVYDZLU1K9EyTApUA2RzyrMp9rgRlBWylIIlFRkmBapnIIuZ0hJmgkc3lQBTzGQEN7mqApjNSwd4VTOQr8yXFDL1IbjtDOTMY/dR1r0+/LZaA1n7yb6/wOsEb+4rlMDYdZR0oSO4uZuYtEkPAO17CP9dA3nCwll3Mlj8iw/nL4ABN/gj8hPAgBsc3KY1kJuTs7Y5yV+B7BBA5nKXrSUsKcGOgJvC/ALSJBp5mBHCFAAAAABJRU5ErkJggg=='); @@ -17,6 +16,6 @@ line-height: 22px; font-size: 12px; vertical-align: middle; - color: rgba(255, 255, 255, 1); + color: rgba(255, 255, 255, 100%); } } diff --git a/packages/meta/lib/ImagePreview/images/emptyImage.png b/packages/meta/es/CompareImage/images/emptyImage.png similarity index 100% rename from packages/meta/lib/ImagePreview/images/emptyImage.png rename to packages/meta/es/CompareImage/images/emptyImage.png diff --git a/packages/meta/lib/ImagePreview/images/percent_background.png b/packages/meta/es/CompareImage/images/percent_background.png similarity index 100% rename from packages/meta/lib/ImagePreview/images/percent_background.png rename to packages/meta/es/CompareImage/images/percent_background.png diff --git a/packages/meta/es/CompareImage/index.d.ts b/packages/meta/es/CompareImage/index.d.ts new file mode 100644 index 0000000..a72b6a9 --- /dev/null +++ b/packages/meta/es/CompareImage/index.d.ts @@ -0,0 +1,3 @@ +import CompareImage from "./CompareImage"; +export type { CompareImageProps } from './CompareImage'; +export default CompareImage; diff --git a/packages/meta/es/CompareImage/index.js b/packages/meta/es/CompareImage/index.js new file mode 100644 index 0000000..7922666 --- /dev/null +++ b/packages/meta/es/CompareImage/index.js @@ -0,0 +1,2 @@ +import CompareImage from "./CompareImage"; +export default CompareImage; \ No newline at end of file diff --git a/packages/meta/src/ImagePreview/index.less b/packages/meta/es/CompareImage/index.less similarity index 100% rename from packages/meta/src/ImagePreview/index.less rename to packages/meta/es/CompareImage/index.less diff --git a/packages/meta/es/ImageEditor/cropper/event.js b/packages/meta/es/ImageEditor/cropper/event.js index c7e0485..c51cbc9 100644 --- a/packages/meta/es/ImageEditor/cropper/event.js +++ b/packages/meta/es/ImageEditor/cropper/event.js @@ -1,6 +1,6 @@ //@ts-nocheck import { addClass, removeClass } from 'rc-util/lib/Dom/class'; -import { addEventlistener, isNumber, get } from '@zhst/func'; +import { addEventListenerWrapper, isNumber, get } from '@zhst/func'; import warn from 'rc-util/lib/warn'; import { getData, getPointer, getOffset, dispatchEvent } from "../utils"; import { @@ -18,12 +18,12 @@ export default { _this$eventHandleList = this.eventHandleList, eventHandleList = _this$eventHandleList === void 0 ? [] : _this$eventHandleList, option = this.option; - var handleCropStart = addEventlistener(container, EVENT_POINTER_DOWN, this.onCropStart.bind(this)); + var handleCropStart = addEventListenerWrapper(container, EVENT_POINTER_DOWN, this.onCropStart.bind(this)); eventHandleList.push(handleCropStart); - var handleCropMove = addEventlistener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove.bind(this)); + var handleCropMove = addEventListenerWrapper(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove.bind(this)); eventHandleList.push(handleCropMove); EVENT_POINTER_UP.trim().split(REGEXP_SPACES).forEach(function (eventName) { - var handleCropEnd = addEventlistener(element.ownerDocument, eventName, _this.onCropEnd.bind(_this)); + var handleCropEnd = addEventListenerWrapper(element.ownerDocument, eventName, _this.onCropEnd.bind(_this)); eventHandleList.push(handleCropEnd); }); }, diff --git a/packages/meta/es/ImageEditor/cropper/viewerBridge.js b/packages/meta/es/ImageEditor/cropper/viewerBridge.js index 0b2a340..ab55778 100644 --- a/packages/meta/es/ImageEditor/cropper/viewerBridge.js +++ b/packages/meta/es/ImageEditor/cropper/viewerBridge.js @@ -1,5 +1,5 @@ //@ts-nocheck -import { addEventlistener } from '@zhst/func'; +import { addEventListenerWrapper } from '@zhst/func'; import { EVENT_WHEEL } from "./constants"; import { EVENT_VIEWER_TRANSFORM_CHANGE } from "../viewer/constants"; export default { @@ -13,12 +13,12 @@ export default { if (this.options.viewer) { var viewer = this.options.viewer; //添加缩放事件 - var handleWhele = addEventlistener(container, EVENT_WHEEL, this.onWheel.bind(this)); + var handleWhele = addEventListenerWrapper(container, EVENT_WHEEL, this.onWheel.bind(this)); eventHandleList.push(handleWhele); //添加事件监听 获取limit crop box & 渲染canvas this.onTransformChange(viewer); this.limited = true; - var handleTransformChange = addEventlistener(viewer.element, EVENT_VIEWER_TRANSFORM_CHANGE, function (event) { + var handleTransformChange = addEventListenerWrapper(viewer.element, EVENT_VIEWER_TRANSFORM_CHANGE, function (event) { _this.onTransformChange(viewer); }); eventHandleList.push(handleTransformChange); diff --git a/packages/meta/es/ImageEditor/viewer/event.js b/packages/meta/es/ImageEditor/viewer/event.js index 93f8638..8f41e1e 100644 --- a/packages/meta/es/ImageEditor/viewer/event.js +++ b/packages/meta/es/ImageEditor/viewer/event.js @@ -5,7 +5,7 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } //@ts-nocheck -import { isNumber, get, addEventListener } from '@zhst/func'; +import { isNumber, get, addEventListenerWrapper } from '@zhst/func'; import { addClass, removeClass } from 'rc-util/lib/Dom/class.js'; import guid from 'rc-util/lib/guid'; import warn from 'rc-util/lib/warn'; @@ -33,27 +33,27 @@ export default { //图片事件 var scaleAble = get(options, 'scaleAble', true); if (scaleAble) { - var handleWhele = addEventListener(canvas, EVENT_WHEEL, this.onWheel.bind(this)); + var handleWhele = addEventListenerWrapper(canvas, EVENT_WHEEL, this.onWheel.bind(this)); eventHandleList.push(handleWhele); } var dragAble = get(options, 'dragAble', true); if (dragAble) { - var handleDragStart = addEventListener(canvas, EVENT_POINTER_DOWN, this.onDragStart.bind(this)); - eventHandleList.push(addEventListener); - var handleDragMove = addEventListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onDragMove.bind(this)); + var handleDragStart = addEventListenerWrapper(canvas, EVENT_POINTER_DOWN, this.onDragStart.bind(this)); + eventHandleList.push(addEventListenerWrapper); + var handleDragMove = addEventListenerWrapper(element.ownerDocument, EVENT_POINTER_MOVE, this.onDragMove.bind(this)); eventHandleList.push(handleDragMove); EVENT_POINTER_UP.trim().split(REGEXP_SPACES).forEach(function (eventName) { - var handleDragEnd = addEventListener(element.ownerDocument, eventName, _this.onDragEnd.bind(_this)); + var handleDragEnd = addEventListenerWrapper(element.ownerDocument, eventName, _this.onDragEnd.bind(_this)); eventHandleList.push(handleDragEnd); }); } //rect事件 - var handleClick = addEventListener(canvas, EVENT_CLICK, this.onClick.bind(this)); + var handleClick = addEventListenerWrapper(canvas, EVENT_CLICK, this.onClick.bind(this)); eventHandleList.push(handleClick); - // const handleLeveal = addEventListener(canvas, EVENT_LEAVEL, this.onLeavel.bind(this)); + // const handleLeveal = addEventListenerWrapper(canvas, EVENT_LEAVEL, this.onLeavel.bind(this)); // eventHandleList.push(handleLeveal); - // const handleEnter = addEventListener(canvas, EVENT_ENTER, this.onEnter.bind(this)); + // const handleEnter = addEventListenerWrapper(canvas, EVENT_ENTER, this.onEnter.bind(this)); // eventHandleList.push(handleEnter); }, unbind: function unbind() { diff --git a/packages/meta/es/ImagePreview/index.d.ts b/packages/meta/es/ImagePreview/index.d.ts deleted file mode 100644 index 31fba43..0000000 --- a/packages/meta/es/ImagePreview/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { FC } from 'react'; -export interface CompaterImageProps { - url: string; - label: string; - openRoll?: boolean; - urls?: Array; - specialTitle: String; - noTargetImageTip?: string; - score?: number; -} -declare const CompaterImage: FC; -export default CompaterImage; diff --git a/packages/meta/es/VideoPlayer/VideoPlayer.d.ts b/packages/meta/es/VideoPlayer/VideoPlayer.d.ts new file mode 100644 index 0000000..cf56091 --- /dev/null +++ b/packages/meta/es/VideoPlayer/VideoPlayer.d.ts @@ -0,0 +1,18 @@ +import React, { Dispatch, ReactElement, SetStateAction } from 'react'; +import { Rect, IScreenshotButtonProp, AlignType } from '@zhst/types'; +import './index.less'; +export interface VideoViewProps { + url: string; + maxDuration?: number; + screenshotButtonAlign?: AlignType; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; + defautlNormalizationRect?: Rect; + onCropChange?: (showCrop: boolean, normalizationRect: null | Rect) => void; +} +export interface VideoViewRef { + cropAble: boolean; + setShowCrop: Dispatch>; + downloadVideoframe: () => void; +} +declare const VideoPlayer: React.ForwardRefExoticComponent>; +export default VideoPlayer; diff --git a/packages/meta/es/VideoPlayer/VideoPlayer.js b/packages/meta/es/VideoPlayer/VideoPlayer.js new file mode 100644 index 0000000..119f86f --- /dev/null +++ b/packages/meta/es/VideoPlayer/VideoPlayer.js @@ -0,0 +1,679 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; +import { noop, get, addEventListenerWrapper, dataURLToBlob, nextTick, toRealNumber, getTransforms, formatDurationTime } from '@zhst/func'; +import Align from 'rc-align'; +import { useLatest, useUpdateEffect, useFullscreen, useUnmount } from '@zhst/hooks'; +import classNames from 'classnames'; +import download from 'downloadjs'; +import { Button, message } from 'antd'; +import Icon from "../iconfont"; +import { Cropper, EVENT_CROP_START, EVENT_CROP_END } from "../ImageEditor"; +import FlvPlayer, { FLV_EVENT } from "./components/FlvPlayer"; +import Range from "./components/Progress"; +import Loading from "./components/Loading"; +import getScreenshotButtonRender from "../BigImagePreview/components/ScreenhotButtons"; +import { CROP_TYPE } from "../utils/constants"; +import { getShowStatus } from "./videoPlayerHelper"; +import "./index.less"; +var componentName = "zhst-image__video-view"; +var VideoPlayer = /*#__PURE__*/forwardRef(function (props, ref) { + var url = props.url, + maxDuration = props.maxDuration, + _props$screenshotButt = props.screenshotButtonAlign, + screenshotButtonAlign = _props$screenshotButt === void 0 ? { + points: ['bl', 'br'], + offset: [6, 0], + overflow: { + adjustX: true, + adjustY: true + } + } : _props$screenshotButt, + _props$screenshotButt2 = props.screenshotButtonRender, + screenshotButtonRender = _props$screenshotButt2 === void 0 ? getScreenshotButtonRender({ + onBigImageActionClick: function onBigImageActionClick() {}, + disableBtn: [] + }) : _props$screenshotButt2, + onCropChange = props.onCropChange, + defaultNormalizationRect = props.defautlNormalizationRect; + var videoType = useMemo(function () { + return url && url.startsWith('http') ? 'mp4' : 'flv'; + }, [url]); + // ========================== 播放 ========================= + //实例参数 + var containerRef = useRef(null); //容器ref + var videoRef = useRef(null); //video 标签dom + var videoInsRef = useRef(null); //flv 实例 + var _useState = useState(0), + _useState2 = _slicedToArray(_useState, 2), + playSeq = _useState2[0], + setPlaySeq = _useState2[1]; // 通过重置playid使FLV组件重新渲染 + var videoRemoveListener = useRef(noop); //移除dom监听的中间函数 + var loadingTimeRef = useRef(0); //最后一次加载时间 + var delayLoadingTimer = useRef(null); //算loading的定时器 + //状态参数 + var _useState3 = useState(false), + _useState4 = _slicedToArray(_useState3, 2), + isReady = _useState4[0], + setIsReady = _useState4[1]; // + var _useState5 = useState(false), + _useState6 = _slicedToArray(_useState5, 2), + isPlay = _useState6[0], + setIsPlay = _useState6[1]; //当前是否播放 + + var _useState7 = useState(false), + _useState8 = _slicedToArray(_useState7, 2), + isEnd = _useState8[0], + setIsEnd = _useState8[1]; //是否播放结束 + var _useState9 = useState(false), + _useState10 = _slicedToArray(_useState9, 2), + isError = _useState10[0], + setIsError = _useState10[1]; //播放出错 + var _useState11 = useState(false), + _useState12 = _slicedToArray(_useState11, 2), + isVideoLoadFinished = _useState12[0], + setIsVideoLoadFinish = _useState12[1]; //是否缓存加载完成 + var _useState13 = useState(0), + _useState14 = _slicedToArray(_useState13, 2), + playTime = _useState14[0], + setPlayTime = _useState14[1]; //当前播放时间 + var _useState15 = useState(true), + _useState16 = _slicedToArray(_useState15, 2), + isLoadingVideo = _useState16[0], + setIsLoadingVideo = _useState16[1]; //是否加载中 + var _useState17 = useState(false), + _useState18 = _slicedToArray(_useState17, 2), + isDelayLoading = _useState18[0], + setIsDelayLoading = _useState18[1]; //显示的转圈loading 延迟0.2s显示 + //设置延迟转圈圈 + var latestIsLoadingVideo = useLatest(isLoadingVideo); + var setIsLoadingVideoWrapper = function setIsLoadingVideoWrapper(isLoading) { + setIsLoadingVideo(function (preLoading) { + if (!preLoading && isLoading) { + loadingTimeRef.current = new Date().getTime(); + } + if (!isLoading) { + loadingTimeRef.current = null; + } + //延迟0。2s相关 + if (!isLoading) { + setIsDelayLoading(false); + } + if (!delayLoadingTimer.current && preLoading) { + delayLoadingTimer.current = setTimeout(function () { + if (latestIsLoadingVideo.current) { + //0.2s后才显示 + setIsDelayLoading(true); + } + delayLoadingTimer.current = null; + }, 200); + } + return isLoading; + }); + }; + // 初始化loading 30s 直接显示错误 + // TODO :逻辑忘记了 不应该是每次init player吗? + useEffect(function () { + var timer = setInterval(function () { + if (loadingTimeRef.current) { + if (new Date().getTime() - loadingTimeRef.current > 1000 * 30) { + checkIsErr(); + } + } + }, 1000); + return function () { + clearInterval(timer); + }; + }, []); + + //结束的时候暂停 保证不播了 + useUpdateEffect(function () { + if (isEnd) { + var _videoInsRef$current, _videoInsRef$current$; + videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current = videoInsRef.current) === null || _videoInsRef$current === void 0 || (_videoInsRef$current$ = _videoInsRef$current.pause) === null || _videoInsRef$current$ === void 0 || _videoInsRef$current$.call(_videoInsRef$current); + } + }, [isEnd]); + + // 捕捉视频播放报错 + var checkIsErr = function checkIsErr() { + setIsError(true); + try { + var _videoInsRef$current2, _videoInsRef$current3; + videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current2 = videoInsRef.current) === null || _videoInsRef$current2 === void 0 || (_videoInsRef$current3 = _videoInsRef$current2.destroy) === null || _videoInsRef$current3 === void 0 || _videoInsRef$current3.call(_videoInsRef$current2); + } catch (error) { + console.error(error); + } + }; + + // 初始化 + var latestMaxDuration = useLatest(maxDuration); + var initPlayer = useCallback(function (ins, dom) { + videoRef.current = dom; + videoInsRef.current = ins; + var maxDuration = latestMaxDuration.current || 0; + //监听播放事件 + var video = dom; + var errorLister = function errorLister(e) { + checkIsErr(); + console.error('视频出错了', e, video.currentTime); + }; + var waitingListener = function waitingListener(e) { + setIsLoadingVideoWrapper(true); + console.debug('视频加载等待', e, video.currentTime); + }; + var playingListener = function playingListener(e) { + setIsLoadingVideoWrapper(false); + setIsError(false); + console.debug('视频从等待中播放', e, video.currentTime); + }; + var playLister = function playLister(e) { + setIsPlay(true); + setIsError(false); + console.debug('提示该视频正在播放中', e, video.currentTime); + }; + var pauseListener = function pauseListener(e) { + setIsPlay(false); + console.debug('暂停播放', e, video.currentTime); + }; + var endedListner = function endedListner(e) { + setIsEnd(true); + setIsVideoLoadFinish(true); + console.debug('视频播放完了', e, video.currentTime); + }; + var timeupdateListner = function timeupdateListner(e) { + var _videoRef$current; + console.debug('视频播放时间更新', e, video.currentTime, (_videoRef$current = videoRef.current) === null || _videoRef$current === void 0 ? void 0 : _videoRef$current.duration, maxDuration); + var nowTime = video.currentTime; + if (nowTime >= maxDuration) { + setIsEnd(true); + setIsVideoLoadFinish(true); + } + setPlayTime(nowTime); + }; + // see https://github.com/bilibili/flv.js/issues/337 + var windowErrorHandle = function windowErrorHandle(errorEvent) { + try { + if (errorEvent['message'] == "Uncaught TypeError: Cannot read property 'flushStashedSamples' of null") { + checkIsErr(); + console.error('视频出错了 window监听', errorEvent); + } + } catch (error) { + console.error(error); + } + }; + video.addEventListener('error', errorLister); + video.addEventListener('waiting', waitingListener); + video.addEventListener('playing', playingListener); + video.addEventListener('play', playLister); + video.addEventListener('pause', pauseListener); + video.addEventListener('ended', endedListner); + video.addEventListener('timeupdate', timeupdateListner); + window.addEventListener('error', windowErrorHandle); + videoRemoveListener.current = function () { + video.removeEventListener('error', errorLister); + video.removeEventListener('waiting', waitingListener); + video.removeEventListener('playing', playingListener); + video.removeEventListener('play', playLister); + video.removeEventListener('pause', pauseListener); + video.removeEventListener('ended', endedListner); + video.removeEventListener('timeupdate', timeupdateListner); + window.removeEventListener('error', windowErrorHandle); + }; + videoInsRef === null || videoInsRef === void 0 || videoInsRef.current.on(FLV_EVENT.ERROR, function (type, errDetail, info) { + checkIsErr(); + console.error('videoInsRef 错误', type, errDetail, info, video.currentTime); + }); + var playPromise = videoInsRef === null || videoInsRef === void 0 ? void 0 : videoInsRef.current.play(); + //先ready 遮挡会导致播放失败 + setIsReady(true); + playPromise.then(function () { + setIsReady(true); + }).catch(function () { + try {} catch (error) {} + // setIsError(true); + for (var _len = arguments.length, arg = new Array(_len), _key = 0; _key < _len; _key++) { + arg[_key] = arguments[_key]; + } + console.error('playPromise视频出错了', arg); + }); + }, []); + useUnmount(function () { + try { + videoRemoveListener.current(); + } catch (e) { + console.error(e); + } + }); + var _reload = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var oldTime; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!videoInsRef.current) { + _context.next = 15; + break; + } + oldTime = videoInsRef.current.currentTime; + videoInsRef.current.currentTime = 0; + + //如果修改时间不成功,则走重新加载的逻辑 + if (!(oldTime === videoInsRef.current.currentTime)) { + _context.next = 14; + break; + } + //重置状态 + setIsReady(false); + setIsPlay(false); + setIsLoadingVideoWrapper(false); + setIsReady(false); + setIsEnd(false); + setIsVideoLoadFinish(false); + setPlayTime(0); + + //清楚dom事件监听 + try { + videoRemoveListener.current(); + } catch (error) { + console.error(error); + } + setPlaySeq(function (pre) { + return pre + 1; + }); + return _context.abrupt("return"); + case 14: + videoInsRef.current.play(); + case 15: + setPlayTime(0); + setIsEnd(false); + case 17: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function reload() { + return _ref.apply(this, arguments); + }; + }(); + var seek = function seek(v) { + if (videoInsRef.current && isVideoLoadFinished) { + setPlayTime(parseFloat(v)); + videoInsRef.current.currentTime = parseFloat(v); + } else { + message.warning('待视频加载完,才可操作进度条'); + } + }; + // ========================== 视频opt bar ========================= + var _useFullscreen = useFullscreen(containerRef, { + pageFullscreen: true + }), + _useFullscreen2 = _slicedToArray(_useFullscreen, 2), + isFullscreen = _useFullscreen2[0], + toggleFullscreen = _useFullscreen2[1].toggleFullscreen; + var showMaxDuration = !!maxDuration ? maxDuration : toRealNumber(get(videoRef, 'current.duration', 0)); + var showSlider = videoInsRef.current && isVideoLoadFinished; + var showStatus = getShowStatus(isDelayLoading, isEnd, isError); + + // ========================== 截图 ========================= + var corpContainerRef = useRef(); + var cropInsRef = useRef(null); + var _useState19 = useState(false), + _useState20 = _slicedToArray(_useState19, 2), + showCrop = _useState20[0], + _setShowCrop = _useState20[1]; + + //回显默认框选 + var isFirstFlagRef = useRef(true); + useEffect(function () { + var isFirst = isFirstFlagRef.current; + if (!isLoadingVideo && isReady && isFirst && defaultNormalizationRect && !showStatus) { + nextTick(function () { + _setShowCrop(true); + }); + } + }, [isLoadingVideo, showStatus]); + + //定位按钮相关参数 + var alginContainerRef = useRef(null); + var alignRef = useRef(null); + var _useState21 = useState(null), + _useState22 = _slicedToArray(_useState21, 2), + cropRect = _useState22[0], + setCropRect = _useState22[1]; + useEffect(function () { + var _videoInsRef$current4, _videoInsRef$current5; + showCrop ? videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current4 = videoInsRef.current) === null || _videoInsRef$current4 === void 0 ? void 0 : _videoInsRef$current4.pause() : videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current5 = videoInsRef.current) === null || _videoInsRef$current5 === void 0 ? void 0 : _videoInsRef$current5.play(); + }, [showCrop]); + useEffect(function () { + var handlerCropStart; + var handlerCropEnd; + setCropRect(null); + if (!isReady) return; + if (showCrop) { + var _canvas$parentNode; + handlerCropStart = addEventListenerWrapper(corpContainerRef.current, EVENT_CROP_START, function () { + setCropRect(null); + }); + handlerCropEnd = addEventListenerWrapper(corpContainerRef.current, EVENT_CROP_END, function (event) { + var _alignRef$current, _alignRef$current$for; + var data = event.detail; + setCropRect({ + x: data.left, + y: data.top, + w: data.width, + h: data.height + }); + alignRef === null || alignRef === void 0 || (_alignRef$current = alignRef.current) === null || _alignRef$current === void 0 || (_alignRef$current$for = _alignRef$current.forceAlign) === null || _alignRef$current$for === void 0 || _alignRef$current$for.call(_alignRef$current); + }); + var video = videoRef.current; + //计算 limitcroppbox + var scale = Math.min(video.offsetWidth / video.videoWidth, video.offsetHeight / video.videoHeight); + var finalVideoWidth = video.videoWidth * scale; + var finalVideoHeight = video.videoHeight * scale; + var cropBoxLimited = { + width: finalVideoWidth, + height: finalVideoHeight, + top: (video.offsetHeight - finalVideoHeight) / 2, + left: (video.offsetWidth - finalVideoWidth) / 2 + }; + //获取视频图片 + var canvas = document.createElement('canvas'); + canvas.width = video.offsetWidth; + canvas.height = video.offsetHeight; + canvas.style.display = 'none'; + document.body.appendChild(canvas); + var ctx = canvas.getContext('2d'); + ctx === null || ctx === void 0 || ctx.drawImage(video, (video.offsetWidth - finalVideoWidth) / 2, (video.offsetHeight - finalVideoHeight) / 2, finalVideoWidth, finalVideoHeight); + var imageData = canvas.toDataURL('image/png'); + (_canvas$parentNode = canvas.parentNode) === null || _canvas$parentNode === void 0 || _canvas$parentNode.removeChild(canvas); + //回显编辑框 + var isFirst = isFirstFlagRef.current; + var initialCropBoxData = null; + if (isFirst && defaultNormalizationRect) { + initialCropBoxData = { + left: defaultNormalizationRect.x * finalVideoWidth + cropBoxLimited.left, + top: defaultNormalizationRect.y * finalVideoHeight + cropBoxLimited.top, + width: defaultNormalizationRect.w * finalVideoWidth, + height: defaultNormalizationRect.h * finalVideoHeight + }; + } + isFirstFlagRef.current = false; + cropInsRef.current = new Cropper(corpContainerRef.current, { + showMask: true, + cropBoxLimited: cropBoxLimited, + img: imageData, + initialCropBoxData: initialCropBoxData + }); + } + return function () { + var _handlerCropStart, _handlerCropEnd, _cropInsRef$current, _cropInsRef$current$d; + (_handlerCropStart = handlerCropStart) === null || _handlerCropStart === void 0 || _handlerCropStart.remove(); + (_handlerCropEnd = handlerCropEnd) === null || _handlerCropEnd === void 0 || _handlerCropEnd.remove(); + cropInsRef === null || cropInsRef === void 0 || (_cropInsRef$current = cropInsRef.current) === null || _cropInsRef$current === void 0 || (_cropInsRef$current$d = _cropInsRef$current.destroy) === null || _cropInsRef$current$d === void 0 || _cropInsRef$current$d.call(_cropInsRef$current); + cropInsRef.current = null; + }; + }, [showCrop, isReady]); + var latestCropRect = useLatest(cropRect); + var getCropInfo = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var _canvas$parentNode2; + var cropRect, video, rectList, extendRectList, selectIndex, scale, finalVideoWidth, finalVideoHeight, canvas, ctx, base64, blobData, file, newRect; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cropRect = latestCropRect.current; + video = videoRef.current; + if (video) { + _context3.next = 4; + break; + } + return _context3.abrupt("return"); + case 4: + rectList = []; + extendRectList = []; + selectIndex = 0; //获取视频图片的url + scale = Math.min(video.offsetWidth / video.videoWidth, video.offsetHeight / video.videoHeight); + finalVideoWidth = video.videoWidth * scale; + finalVideoHeight = video.videoHeight * scale; + canvas = document.createElement('canvas'); + canvas.width = finalVideoWidth; + canvas.height = finalVideoHeight; + canvas.style.display = 'none'; + document.body.appendChild(canvas); + ctx = canvas.getContext('2d'); + ctx.drawImage(video, 0, 0, finalVideoWidth, finalVideoHeight); + base64 = canvas.toDataURL('image/jpeg'); + blobData = dataURLToBlob(base64); + (_canvas$parentNode2 = canvas.parentNode) === null || _canvas$parentNode2 === void 0 || _canvas$parentNode2.removeChild(canvas); + file = new window.File([blobData], "".concat(new Date().getTime())); + newRect = { + w: cropRect.w / finalVideoWidth, + h: cropRect.h / finalVideoHeight, + x: (cropRect.x - (video.offsetWidth - finalVideoWidth) / 2) / finalVideoWidth, + y: (cropRect.y - (video.offsetHeight - finalVideoHeight) / 2) / finalVideoHeight + }; + rectList.push(newRect); + extendRectList.push(newRect); + //扩展框获取imgkey + extendRectList.forEach( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(rect, index) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + extendRectList[index] = _objectSpread({}, rect); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x, _x2) { + return _ref3.apply(this, arguments); + }; + }()); + return _context3.abrupt("return", { + rectList: rectList, + extendRectList: extendRectList, + selectIndex: selectIndex, + file: file + }); + case 26: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function getCropInfo() { + return _ref2.apply(this, arguments); + }; + }(); + + //回调 + useEffect(function () { + //计算归一化crop rect + var normalizationRect = null; + if (showCrop && cropRect) { + var video = videoRef.current; + var scale = Math.min(video.offsetWidth / video.videoWidth, video.offsetHeight / video.videoHeight); + var finalVideoWidth = video.videoWidth * scale; + var finalVideoHeight = video.videoHeight * scale; + var cropBoxLimited = { + width: finalVideoWidth, + height: finalVideoHeight, + top: (video.offsetHeight - finalVideoHeight) / 2, + left: (video.offsetWidth - finalVideoWidth) / 2 + }; + normalizationRect = { + x: (cropRect.x - cropBoxLimited.left) / cropBoxLimited.width, + y: (cropRect.y - cropBoxLimited.top) / cropBoxLimited.height, + w: cropRect.w / cropBoxLimited.width, + h: cropRect.h / cropBoxLimited.height + }; + } + onCropChange === null || onCropChange === void 0 || onCropChange(showCrop, normalizationRect); + }, [showCrop, cropRect]); + + // ========================== 截帧 ========================= + var downloadVideoframe = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var _videoInsRef$current6, _videoInsRef$current7, video, canvas, ctx, base64; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + try { + videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current6 = videoInsRef.current) === null || _videoInsRef$current6 === void 0 || (_videoInsRef$current7 = _videoInsRef$current6.pause) === null || _videoInsRef$current7 === void 0 || _videoInsRef$current7.call(_videoInsRef$current6); + video = videoRef.current; + canvas = document.createElement('canvas'); + ctx = canvas.getContext('2d'); + //当视频处于还未加载出来时,截屏为黑色图片 + if (video.readyState === 0) { + ctx === null || ctx === void 0 || ctx.clearRect(0, 0, canvas.width, canvas.height); + canvas.width = video.offsetWidth; + canvas.height = video.offsetHeight; + // @ts-ignore + ctx.fillStyle = 'black'; + ctx === null || ctx === void 0 || ctx.fillRect(0, 0, canvas.width, canvas.height); + base64 = canvas.toDataURL(); + } else { + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + ctx === null || ctx === void 0 || ctx.drawImage(video, 0, 0, canvas.width, canvas.height); + base64 = canvas.toDataURL('image/png'); + } + download(base64); + } catch (error) { + console.error(error); + } + case 1: + case "end": + return _context4.stop(); + } + }, _callee4); + })), []); + + // ============================== 暴露出去的方法 =============================== + var latestIsReady = useLatest(isReady); + var cropAble = !showStatus && isReady; + useImperativeHandle(ref, function () { + return { + cropAble: cropAble, + setShowCrop: function setShowCrop(dispatch) { + var isReady = latestIsReady.current; + if (!isReady) return; + _setShowCrop(dispatch); + }, + downloadVideoframe: downloadVideoframe + }; + }); + return /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName)), + ref: containerRef + }, url && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(FlvPlayer, { + playId: playSeq, + autoPlay: true, + className: classNames("".concat(componentName, "-flv")), + type: videoType, + url: url, + config: { + enableStashBuffer: true, + stashInitialSize: 1024 * 700, + isLive: true, + hasAudio: false, + hasVideo: true + }, + onCreat: initPlayer + }), /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "-crop-container")), + ref: corpContainerRef, + style: { + display: isFullscreen ? 'none' : 'block' + } + }), showCrop && cropRect && screenshotButtonRender && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { + ref: alginContainerRef, + className: classNames("".concat(componentName, "-align")), + style: Object.assign({ + width: cropRect.w, + height: cropRect.h + }, getTransforms({ + translateX: cropRect.x, + translateY: cropRect.y + })) + }), /*#__PURE__*/React.createElement(Align, { + ref: alignRef, + monitorWindowResize: true, + align: screenshotButtonAlign, + target: function target() { + return alginContainerRef.current; + } + }, screenshotButtonRender({ + model: 'IMAGE', + getCropInfo: getCropInfo, + setShowCrop: _setShowCrop, + cropType: CROP_TYPE['CUSTOM'] + }))), !showCrop && /*#__PURE__*/React.createElement("div", { + className: "".concat(componentName, "-opt") + }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Button, { + type: "text", + onClick: function onClick(e) { + if (!isPlay) { + var _videoInsRef$current8; + //播放中暂停 + videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current8 = videoInsRef.current) === null || _videoInsRef$current8 === void 0 || _videoInsRef$current8.play(); + _setShowCrop(false); + } else { + var _videoInsRef$current9; + videoInsRef === null || videoInsRef === void 0 || (_videoInsRef$current9 = videoInsRef.current) === null || _videoInsRef$current9 === void 0 || _videoInsRef$current9.pause(); + } + } + }, /*#__PURE__*/React.createElement(Icon, { + styles: { + color: '#fff', + display: 'flex' + }, + color: "#1890ff", + icon: !isPlay ? 'icon-shipinbofang' : 'icon-shipinzanting' + }))), /*#__PURE__*/React.createElement("div", { + className: "".concat(componentName, "-opt-range"), + onClick: function onClick(e) { + e.stopPropagation(); + } + }, /*#__PURE__*/React.createElement(Range, { + value: playTime, + min: 0, + max: showMaxDuration, + showSlider: showSlider, + onChange: seek + }), /*#__PURE__*/React.createElement("div", null, formatDurationTime(playTime), "/", formatDurationTime(showMaxDuration))), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Button, { + type: "text", + onClick: function onClick(e) { + e.stopPropagation(); + toggleFullscreen(); + } + }, /*#__PURE__*/React.createElement(Icon, { + styles: { + color: '#fff', + display: 'flex' + }, + size: 18, + icon: isFullscreen ? 'icon-cancle_fullscreen' : 'icon-fullscreen' + })))), !!showStatus && /*#__PURE__*/React.createElement(Loading, { + status: showStatus, + reload: function reload() { + return _reload(); + } + }))); +}); +export default VideoPlayer; \ No newline at end of file diff --git a/packages/meta/es/VideoPlayer/components/FlvPlayer/index.d.ts b/packages/meta/es/VideoPlayer/components/FlvPlayer/index.d.ts new file mode 100644 index 0000000..646b267 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/FlvPlayer/index.d.ts @@ -0,0 +1,46 @@ +import React, { Component, CSSProperties } from 'react'; +import flvjs from 'flv.js'; +export declare const FLV_EVENT: Readonly; +export interface VideoPlayerProps { + className: string; + style?: CSSProperties; + type: string; + isLive?: boolean; + cors?: boolean; + withCredentials?: boolean; + playId?: number; + hasAudio?: boolean; + hasVideo?: boolean; + duration?: number; + filesize?: number; + url?: string; + autoPlay?: boolean; + onCreat?: any; + /** + * @see https://github.com/Bilibili/flv.js/blob/master/docs/api.md#config + */ + config: object; +} +export default class VideoPlayer extends Component { + state: { + curPlayUrl: string; + shouldReinit: boolean; + }; + flvPlayer: any; + videoElement: null; + static getDerivedStateFromProps: (nextProps: { + url?: any; + playId?: any; + }, prevState: { + curPlayUrl?: any; + playId?: any; + }) => { + playId: any; + curPlayUrl: any; + shouldReinit: boolean; + } | null; + initFlv: ($video: null) => void; + componentWillUnmount(): void; + componentDidUpdate(): void; + render(): React.JSX.Element; +} diff --git a/packages/meta/es/VideoPlayer/components/FlvPlayer/index.js b/packages/meta/es/VideoPlayer/components/FlvPlayer/index.js new file mode 100644 index 0000000..8514dcd --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/FlvPlayer/index.js @@ -0,0 +1,152 @@ +var _excluded = ["className", "autoPlay", "config", "onCreat", "playId"]; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +import React, { Component } from 'react'; +import flvjs from 'flv.js'; +import { isEqual } from '@zhst/func'; +export var FLV_EVENT = flvjs.Events; +var VideoPlayer = /*#__PURE__*/function (_Component) { + _inherits(VideoPlayer, _Component); + var _super = _createSuper(VideoPlayer); + function VideoPlayer() { + var _this; + _classCallCheck(this, VideoPlayer); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty(_assertThisInitialized(_this), "state", { + curPlayUrl: '', + shouldReinit: false + }); + _defineProperty(_assertThisInitialized(_this), "flvPlayer", null); + _defineProperty(_assertThisInitialized(_this), "videoElement", null); + _defineProperty(_assertThisInitialized(_this), "initFlv", function ($video) { + _this.videoElement = $video; + var _this$props = _this.props, + className = _this$props.className, + _this$props$autoPlay = _this$props.autoPlay, + autoPlay = _this$props$autoPlay === void 0 ? true : _this$props$autoPlay, + _this$props$config = _this$props.config, + config = _this$props$config === void 0 ? {} : _this$props$config, + onCreat = _this$props.onCreat, + playId = _this$props.playId, + others = _objectWithoutProperties(_this$props, _excluded); + if ($video) { + if (flvjs.isSupported() && _this.props.url && _this.props.url) { + var reload = function reload() { + if (_this.flvPlayer && _this.flvPlayer.destroy) { + try { + _this.flvPlayer.destroy(); + } catch (error) { + console.error(error); + } + } + var flvPlayer = flvjs.createPlayer(_objectSpread({}, others), _objectSpread({ + deferLoadAfterSourceOpen: false + }, config)); + flvPlayer.attachMediaElement($video); + flvPlayer.load(); + _this.flvPlayer = flvPlayer; + // @ts-ignore + var controller = _this.flvPlayer._transmuxer._controller; + var wsLoader = controller._ioctl._loader; + var oldWsOnCompleteFunc = wsLoader._onComplete; + wsLoader._onComplete = function () { + if (!controller._remuxer) { + controller._remuxer = { + destroy: function destroy() { + console.log('组件销毁'); + }, + flushStashedSamples: function flushStashedSamples() { + console.log("flushStashedSamples"); + } + }; + } + oldWsOnCompleteFunc(); + }; + _this.flvPlayer.reload = reload; + onCreat && onCreat(_this.flvPlayer, $video); + }; + reload(); + onCreat && onCreat(_this.flvPlayer, $video); + } + } + }); + return _this; + } + _createClass(VideoPlayer, [{ + key: "componentWillUnmount", + value: function componentWillUnmount() { + if (this.flvPlayer) { + var _this$flvPlayer, _this$flvPlayer2; + (_this$flvPlayer = this.flvPlayer) === null || _this$flvPlayer === void 0 || _this$flvPlayer.unload(); + (_this$flvPlayer2 = this.flvPlayer) === null || _this$flvPlayer2 === void 0 || _this$flvPlayer2.detachMediaElement(); + } + } + }, { + key: "componentDidUpdate", + value: function componentDidUpdate() { + if (this.state.shouldReinit) { + this.setState({ + shouldReinit: false + }); + this.initFlv(this.videoElement); + } + } + }, { + key: "render", + value: function render() { + var _this$props2 = this.props, + className = _this$props2.className, + style = _this$props2.style; + return /*#__PURE__*/React.createElement("video", { + muted: true, + preload: "metadata", + className: className + // controls={true} + , + style: Object.assign({ + width: '100%', + height: '100%' + }, style ? style : {}), + ref: this.initFlv + }); + } + }]); + return VideoPlayer; +}(Component); +_defineProperty(VideoPlayer, "getDerivedStateFromProps", function (nextProps, prevState) { + var _nextProps$playId = nextProps.playId, + playId = _nextProps$playId === void 0 ? 0 : _nextProps$playId; + var _prevState$playId = prevState.playId, + prePlayId = _prevState$playId === void 0 ? 0 : _prevState$playId; + if (nextProps.url !== undefined) { + if (!isEqual(nextProps.url, prevState.curPlayUrl) || !isEqual(playId, prePlayId)) { + return { + playId: playId, + curPlayUrl: nextProps.url, + shouldReinit: true + }; + } + } + // 否则,对于state不进行任何操作 + return null; +}); +export { VideoPlayer as default }; \ No newline at end of file diff --git a/packages/meta/es/VideoPlayer/components/Loading/index.d.ts b/packages/meta/es/VideoPlayer/components/Loading/index.d.ts new file mode 100644 index 0000000..1509947 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/Loading/index.d.ts @@ -0,0 +1,8 @@ +import { FC } from 'react'; +import './index.less'; +export interface ILoading { + status: 'LOADING' | 'COMPLETED' | 'END' | 'ERROR' | null; + reload: () => void; +} +declare const Loading: FC; +export default Loading; diff --git a/packages/meta/es/VideoPlayer/components/Loading/index.js b/packages/meta/es/VideoPlayer/components/Loading/index.js new file mode 100644 index 0000000..d7d18b6 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/Loading/index.js @@ -0,0 +1,46 @@ +import React from 'react'; +import { Spin } from 'antd'; +import classNames from 'classnames'; +import Icon from "../../../iconfont"; +import "./index.less"; +var componentName = "zhst-image__video-view"; +var Loading = function Loading(props) { + var status = props.status, + reload = props.reload; + return /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "__player-mask")), + onClick: function onClick(e) { + e.stopPropagation(); + } + }, status === 'LOADING' && /*#__PURE__*/React.createElement(Spin, { + tip: "\u52A0\u8F7D\u4E2D...", + spinning: status === 'LOADING' + }), status === 'END' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { + onClick: function onClick() { + reload(); + }, + className: classNames("".concat(componentName, "__icon-wraper")) + }, /*#__PURE__*/React.createElement(Icon, { + styles: { + fill: '#ffffff', + color: '#ffffff' + }, + size: 54, + icon: 'icon-shuaxin' + })), /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "__player-mask-title")) + }, '点击刷新后,将重新播放')), status === 'ERROR' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "__icon-wraper")) + }, /*#__PURE__*/React.createElement(Icon, { + styles: { + color: '#ffffff' + }, + size: 54, + icon: 'icon-jiazaishibai' + })), /*#__PURE__*/React.createElement("div", { + className: classNames("".concat(componentName, "__player-mask-title")) + }, '视频加载失败,', /*#__PURE__*/React.createElement("a", { + onClick: reload + }, " ", '刷新')))); +}; +export default Loading; \ No newline at end of file diff --git a/packages/meta/es/VideoPlayer/components/Loading/index.less b/packages/meta/es/VideoPlayer/components/Loading/index.less new file mode 100644 index 0000000..b6c11a2 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/Loading/index.less @@ -0,0 +1,53 @@ +.zhst-image__video-view__player-mask { + position: absolute; + width: 100%; + height: 100%; + z-index: 99; + top: 0; + right: 0; + bottom: 0; + left: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: rgb(4 4 4 / 70%); + + &--bg { + z-index: 999; + background-color: rgb(4 4 4 / 100%); + } + + i { + cursor: pointer; + } + + &-title { + margin-top: 12px; + color: #fff; + text-align: center; + + & a { + color: #09f; + cursor: pointer; + text-decoration: underline; + } + } +} + +.zhst-image__video-view__icon-wraper { + display: flex; + width: 80px; + height: 80px; + align-items: center; + justify-content: center; + background-color: rgb(255 255 255 / 10%); + border-radius: 50%; + cursor: pointer; + line-height: 80px; + text-align: center; + + // &:hover { + // background: #0099ff; + // } +} diff --git a/packages/meta/es/VideoPlayer/components/Progress/index.d.ts b/packages/meta/es/VideoPlayer/components/Progress/index.d.ts new file mode 100644 index 0000000..7fb0a10 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/Progress/index.d.ts @@ -0,0 +1,10 @@ +import React from 'react'; +import type { SliderSingleProps } from 'antd'; +import './index.less'; +export interface RangeWrapperProps extends SliderSingleProps { + showSlider: boolean; + className?: string; + min: number; +} +export declare const Range: React.FC; +export default Range; diff --git a/packages/meta/es/VideoPlayer/components/Progress/index.js b/packages/meta/es/VideoPlayer/components/Progress/index.js new file mode 100644 index 0000000..0eeb850 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/Progress/index.js @@ -0,0 +1,20 @@ +var _excluded = ["className", "style", "showSlider"]; +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } +import React from 'react'; +import classNames from 'classnames'; +import { Slider } from 'antd'; +import "./index.less"; +var componentName = "zhst-image__range"; +export var Range = function Range(props) { + var className = props.className, + style = props.style, + _props$showSlider = props.showSlider, + showSlider = _props$showSlider === void 0 ? true : _props$showSlider, + others = _objectWithoutProperties(props, _excluded); + return /*#__PURE__*/React.createElement("div", { + style: style, + className: classNames("".concat(componentName), !showSlider && "".concat(componentName, "--no-slider"), className) + }, /*#__PURE__*/React.createElement(Slider, others)); +}; +export default Range; \ No newline at end of file diff --git a/packages/meta/es/VideoPlayer/components/Progress/index.less b/packages/meta/es/VideoPlayer/components/Progress/index.less new file mode 100644 index 0000000..e922211 --- /dev/null +++ b/packages/meta/es/VideoPlayer/components/Progress/index.less @@ -0,0 +1,49 @@ +.zhst-image__range { + position: relative; + + &--no-slider { + .next-range-slider { + display: none; + } + } + + & .next-range .next-range-track { + height: 8px; + margin-top: -4px; + border-radius: 8px; + } + + & .next-range .next-range-selected { + height: 8px; + margin-top: -4px; + border-radius: 8px; + } + + & .next-range .next-range-slider-inner { + width: 14px; + height: 14px; + border-color: #fff; + margin-top: -7px; + margin-left: -7px; + background-color: #0098ff; + } + + & .next-range .next-range-slider { + width: 14px; + height: 14px; + margin-top: -7px; + margin-left: -7px; + } + + & .next-range.simulation-click>.next-range-slider-inner { + border: 2px solid #fff !important; + } + + & .next-range .next-range-frag.next-range-active .next-range-slider .next-range-slider-inner { + border: 2px solid #fff !important; + } + + & .next-range .next-range-slider.next-range-slider-moving .next-range-slider-inner { + border: 2px solid #fff !important; + } +} diff --git a/packages/meta/es/VideoPlayer/index.d.ts b/packages/meta/es/VideoPlayer/index.d.ts new file mode 100644 index 0000000..a1993e1 --- /dev/null +++ b/packages/meta/es/VideoPlayer/index.d.ts @@ -0,0 +1,3 @@ +import VideoPlayer from './VideoPlayer'; +export type { VideoViewProps, VideoViewRef } from './VideoPlayer'; +export default VideoPlayer; diff --git a/packages/meta/es/VideoPlayer/index.js b/packages/meta/es/VideoPlayer/index.js new file mode 100644 index 0000000..5863364 --- /dev/null +++ b/packages/meta/es/VideoPlayer/index.js @@ -0,0 +1,2 @@ +import VideoPlayer from "./VideoPlayer"; +export default VideoPlayer; \ No newline at end of file diff --git a/packages/meta/es/VideoPlayer/index.less b/packages/meta/es/VideoPlayer/index.less new file mode 100644 index 0000000..181e65c --- /dev/null +++ b/packages/meta/es/VideoPlayer/index.less @@ -0,0 +1,75 @@ +.zhst-image__video-view { + position: relative; + overflow: hidden; + width: 100%; + height: 532px; + background-color: #333; + + // &-flv { + // width: 85%; + // } + &-screenshot { + position: absolute; + z-index: 10; + } + + &-crop-container { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + } + + &-align { + position: absolute; + top: 0; + left: 0; + pointer-events: none; + } + + &-opt { + position: absolute; + z-index: 99; + bottom: 0; + display: flex; + width: 100%; + height: 32px; + box-sizing: border-box; + align-items: center; + padding: 0 12px; + background-color: rgb(0 0 0 / 80%); + line-height: 32px; + + &>div:first-child { + display: flex; + align-items: center; + margin-right: 12px; + } + + &>div:last-child { + display: flex; + align-items: center; + margin-left: 12px; + } + + &-range { + display: flex; + height: 32px; + flex: 1; + align-items: center; + line-height: 32px; + text-align: center; + + &>div:first-child { + flex: 1; + } + + &>div:last-child { + width: 100px; + margin-left: 8px; + color: #fff; + } + } + } +} diff --git a/packages/meta/es/VideoPlayer/videoPlayerHelper.d.ts b/packages/meta/es/VideoPlayer/videoPlayerHelper.d.ts new file mode 100644 index 0000000..661a7c1 --- /dev/null +++ b/packages/meta/es/VideoPlayer/videoPlayerHelper.d.ts @@ -0,0 +1 @@ +export declare function getShowStatus(isLoadingVideo: boolean, isEnd: boolean, isError: boolean): string | null; diff --git a/packages/meta/es/VideoPlayer/videoPlayerHelper.js b/packages/meta/es/VideoPlayer/videoPlayerHelper.js new file mode 100644 index 0000000..b5e91eb --- /dev/null +++ b/packages/meta/es/VideoPlayer/videoPlayerHelper.js @@ -0,0 +1,13 @@ +export function getShowStatus(isLoadingVideo, isEnd, isError) { + var status = null; + if (isLoadingVideo) { + status = 'LOADING'; + } + if (isError) { + status = 'ERROR'; + } + if (isEnd) { + status = 'END'; + } + return status; +} \ No newline at end of file diff --git a/packages/meta/es/iconfont/iconfont.css b/packages/meta/es/iconfont/iconfont.css new file mode 100644 index 0000000..8bde390 --- /dev/null +++ b/packages/meta/es/iconfont/iconfont.css @@ -0,0 +1,1679 @@ +@font-face { + font-family: iconfont; /* Project id 1739270 */ + src: url('iconfont.woff2?t=1689583241972') format('woff2'), + url('iconfont.woff?t=1689583241972') format('woff'), + url('iconfont.ttf?t=1689583241972') format('truetype'); +} + +.iconfont { + font-family: iconfont !important; + font-size: 16px; + font-style: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.icon-danganxiangqing_hangweifenxi::before { + content: "\e78d"; +} + +.icon-danganxiangqing_shujuganzhi::before { + content: "\e78e"; +} + +.icon-danganxiangqing_huodongguiji::before { + content: "\e78f"; +} + +.icon-danganxiangqing_jibenxinxi::before { + content: "\e7ea"; +} + +.icon-danganxiangqing_fushuwupin::before { + content: "\e7eb"; +} + +.icon-danganxiangqing_jizhanyingyong::before { + content: "\e7ec"; +} + +.icon-jiarudanganku::before { + content: "\e787"; +} + +.icon-dangankunor::before { + content: "\e793"; +} + +.icon-bukongrenwuselect::before { + content: "\e799"; +} + +.icon-bukongrenwunor1::before { + content: "\e79a"; +} + +.icon-dangankuselect::before { + content: "\e79b"; +} + +.icon-jizhanfanor::before { + content: "\e79c"; +} + +.icon-feijidongchechaxunnor::before { + content: "\e79d"; +} + +.icon-jidongchechaxunselect::before { + content: "\e79e"; +} + +.icon-a-lixianfenxiselect2::before { + content: "\e7a1"; +} + +.icon-huisufenxiselect::before { + content: "\e7a2"; +} + +.icon-jizhanfaselect::before { + content: "\e7a3"; +} + +.icon-mubiaojiansuonor::before { + content: "\e7ae"; +} + +.icon-lurenkuselect::before { + content: "\e7b1"; +} + +.icon-shujujiashicangselect::before { + content: "\e7b2"; +} + +.icon-shishijiexiselect::before { + content: "\e7b4"; +} + +.icon-shishijiexinor::before { + content: "\e7b9"; +} + +.icon-jidongchechaxunnor::before { + content: "\e7c1"; +} + +.icon-lurenkunor1::before { + content: "\e7cf"; +} + +.icon-mubiaotezhengchaxunnor::before { + content: "\e7e1"; +} + +.icon-yujingjiluselect::before { + content: "\e7e2"; +} + +.icon-mubiaotezhengchaxunselect::before { + content: "\e7e3"; +} + +.icon-feijidongchechaxunselect::before { + content: "\e7e4"; +} + +.icon-yujingjilunor::before { + content: "\e7e5"; +} + +.icon-lixianfenxiselect::before { + content: "\e7e6"; +} + +.icon-huisufenxinor::before { + content: "\e7e7"; +} + +.icon-shujujiashicangnor::before { + content: "\e7e8"; +} + +.icon-mubiaojiansuoselect::before { + content: "\e7e9"; +} + +.icon-kuangxuangongju::before { + content: "\e796"; +} + +.icon-fengniao::before { + content: "\e792"; +} + +.icon-zhankai::before { + content: "\e790"; +} + +.icon-shouqi::before { + content: "\e791"; +} + +.icon-shijian::before { + content: "\e786"; +} + +.icon-dingwei2::before { + content: "\e613"; +} + +.icon-renyuan::before { + content: "\e784"; +} + +.icon-houtai::before { + content: "\e785"; +} + +.icon-zuo::before { + content: "\e781"; +} + +.icon-you::before { + content: "\e783"; +} + +.icon-kakou::before { + content: "\e780"; +} + +.icon-yujing1::before { + content: "\e77e"; +} + +.icon-yuan2::before { + content: "\e77d"; +} + +.icon-moxingpengzhuang::before { + content: "\e777"; +} + +.icon-moxingpengzhuangnor::before { + content: "\e778"; +} + +.icon-lurenku::before { + content: "\e77b"; +} + +.icon-lurenkunor::before { + content: "\e77c"; +} + +.icon-shiming::before { + content: "\e776"; +} + +.icon-suoxiao2::before { + content: "\e774"; +} + +.icon-fangda1::before { + content: "\e775"; +} + +.icon-guanbi2::before { + content: "\e772"; +} + +.icon-fanhui1::before { + content: "\e773"; +} + +.icon-xiansuomopai::before { + content: "\e76f"; +} + +.icon-xiansuomopainor::before { + content: "\e76e"; +} + +.icon-zhajiyujing::before { + content: "\e770"; +} + +.icon-zhajiyujingnor::before { + content: "\e771"; +} + +.icon-zhuizongpeizhi::before { + content: "\e76c"; +} + +.icon-zhuizongpeizhinor::before { + content: "\e76d"; +} + +.icon-dapingqiehuan::before { + content: "\e76b"; +} + +.icon-xuanze::before { + content: "\e769"; +} + +.icon-shaixuan1::before { + content: "\e76a"; +} + +.icon-chekashebei::before { + content: "\e764"; +} + +.icon-imsishebei::before { + content: "\e765"; +} + +.icon-xingtishebei::before { + content: "\e766"; +} + +.icon-renlianshebei::before { + content: "\e767"; +} + +.icon-wifishebei::before { + content: "\e768"; +} + +.icon-a-miaozhun2::before { + content: "\e762"; +} + +.icon-a-bianzu19::before { + content: "\e763"; +} + +.icon-fanye::before { + content: "\e75e"; +} + +.icon-shenfenzheng::before { + content: "\e75f"; +} + +.icon-dizhi::before { + content: "\e760"; +} + +.icon-guanbi::before { + content: "\e761"; +} + +.icon-dianwei1::before { + content: "\e75b"; +} + +.icon-weikakou::before { + content: "\e757"; +} + +.icon-weikakounor::before { + content: "\e758"; +} + +.icon-changsuoma::before { + content: "\e759"; +} + +.icon-changsuomanor::before { + content: "\e75a"; +} + +.icon-yujing::before { + content: "\e756"; +} + +.icon-jiansuonor::before { + content: "\e747"; +} + +.icon-tonghangrenfenxinor1::before { + content: "\e748"; +} + +.icon-zhinengyanpannor::before { + content: "\e749"; +} + +.icon-bukongyujingnor::before { + content: "\e74a"; +} + +.icon-bukongrenwunor::before { + content: "\e74b"; +} + +.icon-dianziditunor::before { + content: "\e754"; +} + +.icon-zhuizongnor1::before { + content: "\e755"; +} + +.icon-zhuizong1::before { + content: "\e746"; +} + +.icon-bukongrenwu3::before { + content: "\e74c"; +} + +.icon-dianziditu::before { + content: "\e74d"; +} + +.icon-bukongyujing::before { + content: "\e750"; +} + +.icon-tonghangrenfenxi1::before { + content: "\e751"; +} + +.icon-zhinengyanpan::before { + content: "\e752"; +} + +.icon-jiansuo1::before { + content: "\e753"; +} + +.icon-kaiqijulei::before { + content: "\e745"; +} + +.icon-tongbu::before { + content: "\e744"; +} + +.icon-tonghangrenfenxi::before { + content: "\e743"; +} + +.icon-tonghangrenfenxinor::before { + content: "\e742"; +} + +.icon-jizhanyingyong::before { + content: "\e741"; +} + +.icon-haikangrenlianbukongnor::before { + content: "\e740"; +} + +.icon-haikangrenlianbukong::before { + content: "\e73f"; +} + +.icon-tuozhanshouduantishi::before { + content: "\e73e"; +} + +.icon-fanhuimopailiebiao::before { + content: "\e73d"; +} + +.icon-toukuijiancenor::before { + content: "\e73c"; +} + +.icon-toukuijiance::before { + content: "\e718"; +} + +.icon-zhuixing::before { + content: "\e717"; +} + +.icon-tishi4::before { + content: "\e73b"; +} + +.icon-a-shaixuanfeiji::before { + content: "\e733"; +} + +.icon-a-zidongtiaozhengfanweifeiji::before { + content: "\e73a"; +} + +.icon-heziyunwei::before { + content: "\e739"; +} + +.icon-qiehuan::before { + content: "\e738"; +} + +.icon-disanfangxiaoxinor::before { + content: "\e737"; +} + +.icon-disanfangxiaoxi::before { + content: "\e736"; +} + +.icon-daohang::before { + content: "\e735"; +} + +.icon-yonghu::before { + content: "\e734"; +} + +.icon-feiji::before { + content: "\e732"; +} + +.icon-jieshuzhuizong::before { + content: "\e730"; +} + +.icon-huisuzhoubian::before { + content: "\e731"; +} + +.icon-jixuzhuizong::before { + content: "\e72d"; +} + +.icon-tiaozhengfanwei::before { + content: "\e72e"; +} + +.icon-jiansuo::before { + content: "\e72f"; +} + +.icon-guiji::before { + content: "\e72c"; +} + +.icon-jichuxinxi::before { + content: "\e72b"; +} + +.icon-danganzhaiyao::before { + content: "\e72a"; +} + +.icon-jingzhunbukongicon_on::before { + content: "\e728"; +} + +.icon-jingzhunbukongicon_off::before { + content: "\e729"; +} + +.icon-tiaozhuan::before { + content: "\e727"; +} + +.icon-shezhi::before { + content: "\e726"; +} + +.icon-bangzhu1::before { + content: "\e725"; +} + +.icon-shuaxin1::before { + content: "\e724"; +} + +.icon-duosucaibeifen::before { + content: "\e722"; +} + +.icon-duosucai::before { + content: "\e723"; +} + +.icon-shujutongji::before { + content: "\e721"; +} + +.icon-renlian::before { + content: "\e71c"; +} + +.icon-xingti::before { + content: "\e71d"; +} + +.icon-jidongche::before { + content: "\e71e"; +} + +.icon-huisufenxi4::before { + content: "\e71f"; +} + +.icon-lixianfenxi4::before { + content: "\e720"; +} + +.icon-feijidongche::before { + content: "\e71b"; +} + +.icon-shujudaping::before { + content: "\e71a"; +} + +.icon-peizhisuanfa::before { + content: "\e719"; +} + +.icon-zhuizong::before { + content: "\e715"; +} + +.icon-zhuizongnor::before { + content: "\e716"; +} + +.icon-dianwei::before { + content: "\e714"; +} + +.icon-Container::before { + content: "\e713"; +} + +.icon-Attachment::before { + content: "\e712"; +} + +.icon-cha::before { + content: "\e711"; +} + +.icon-gou::before { + content: "\e710"; +} + +.icon-daoru::before { + content: "\e70f"; +} + +.icon-quanxijiansuo::before { + content: "\e70e"; +} + +.icon-chakanjiankong::before { + content: "\e70c"; +} + +.icon-tishi3::before { + content: "\e70d"; +} + +.icon-heiyemoshi::before { + content: "\e70b"; +} + +.icon-zhengchangmoshi::before { + content: "\e70a"; +} + +.icon-dingwei1::before { + content: "\e709"; +} + +.icon-paixu::before { + content: "\e708"; +} + +.icon-tianjiayuan::before { + content: "\e707"; +} + +.icon-juleidangankunor::before { + content: "\e705"; +} + +.icon-juleidanganku::before { + content: "\e706"; +} + +.icon-guanlian::before { + content: "\e704"; +} + +.icon-renlianbiaozhu::before { + content: "\e703"; +} + +.icon-juleijieguo::before { + content: "\e6ec"; +} + +.icon-juleirenwunor::before { + content: "\e6fb"; +} + +.icon-juleijieguonor::before { + content: "\e701"; +} + +.icon-juleirenwu::before { + content: "\e702"; +} + +.icon-zhongzhi3::before { + content: "\e8ff"; +} + +.icon-xuanzhuan1::before { + content: "\e6fd"; +} + +.icon-shuangmubiaozhu1::before { + content: "\e700"; +} + +.icon-shoudongkuangxuan::before { + content: "\e6f9"; +} + +.icon-zanting1::before { + content: "\e6fe"; +} + +.icon-zhongzhi1::before { + content: "\e6ff"; +} + +.icon-shoudong::before { + content: "\e6fa"; +} + +.icon-zidong::before { + content: "\e6fc"; +} + +.icon-zhenduan::before { + content: "\e6f8"; +} + +.icon-Check-Circle-Fill1::before { + content: "\e6f3"; +} + +.icon-Info--Circle-Fill::before { + content: "\e6f4"; +} + +.icon-Close-Circle-Fill::before { + content: "\e6f5"; +} + +.icon-Warning-Circle-Fill::before { + content: "\e6f6"; +} + +.icon-Question-Circle-Fill::before { + content: "\e6f7"; +} + +.icon-zancunjia::before { + content: "\e6f2"; +} + +.icon-Check-Circle-Fill::before { + content: "\e6f1"; +} + +.icon-tupianji::before { + content: "\e6f0"; +} + +.icon-quanping1::before { + content: "\e6ed"; +} + +.icon-yinliang::before { + content: "\e6ee"; +} + +.icon-suoxiao1::before { + content: "\e6ef"; +} + +.icon-home::before { + content: "\e6eb"; +} + +.icon-zuixiaohua::before { + content: "\e6e9"; +} + +.icon-zuidahua::before { + content: "\e6ea"; +} + +.icon-biaozhunhua::before { + content: "\e6e6"; +} + +.icon-julei::before { + content: "\e6e5"; +} + +.icon-bianzu::before { + content: "\e6e7"; +} + +.icon-bianzu3::before { + content: "\e6e8"; +} + +.icon-bianzu7::before { + content: "\e6e3"; +} + +.icon-bianzu2::before { + content: "\e6e4"; +} + +.icon-kapianqiehuan::before { + content: "\e6e2"; +} + +.icon-duobianxing1::before { + content: "\e6e0"; +} + +.icon-fang1::before { + content: "\e6e1"; +} + +.icon-yuan1::before { + content: "\e6df"; +} + +.icon-cejuli::before { + content: "\e6de"; +} + +.icon-wanggekuangxuannor::before { + content: "\e6dc"; +} + +.icon-lujingkuangxuannor::before { + content: "\e6dd"; +} + +.icon-chuansuo::before { + content: "\e6db"; +} + +.icon-bianyuanhezinor::before { + content: "\e6d8"; +} + +.icon-wujiankuhov::before { + content: "\e6d9"; +} + +.icon-caozuorizhinor::before { + content: "\e6da"; +} + +.icon-collect_dot::before { + content: "\e619"; +} + +.icon-chuxiandingweibg::before { + content: "\e6d4"; +} + +.icon-chuxiandingweiicon::before { + content: "\e6d5"; +} + +.icon-shexiangtoudingweibg::before { + content: "\e6d6"; +} + +.icon-shexiangtoudingweiicon::before { + content: "\e6d7"; +} + +.icon-xiafajieguo::before { + content: "\e6d2"; +} + +.icon-daochu1::before { + content: "\e6d3"; +} + +.icon-zuijinchuxian::before { + content: "\e6cc"; +} + +.icon-leijizhuapai::before { + content: "\e6d0"; +} + +.icon-yichangshijian::before { + content: "\e6d1"; +} + +.icon-dingwei::before { + content: "\e6cb"; +} + +.icon-tupian::before { + content: "\e6ad"; +} + +.icon-wenti::before { + content: "\e6ac"; +} + +.icon-lixian1::before { + content: "\e6ab"; +} + +.icon-yichang::before { + content: "\e6a8"; +} + +.icon-zhuixing-xiugaidianwei::before { + content: "\e6a7"; +} + +.icon-wenhao1::before { + content: "\e69e"; +} + +.icon-ditu_dingwei::before { + content: "\e69d"; +} + +.icon-ditu_fangda::before { + content: "\e689"; +} + +.icon-ditu_suoxiao::before { + content: "\e69a"; +} + +.icon-chakanbukongrenwu::before { + content: "\e688"; +} + +.icon-lietu::before { + content: "\e687"; +} + +.icon-zhongzhi::before { + content: "\e67e"; +} + +.icon-xialada::before { + content: "\e67f"; +} + +.icon-zhinengguanlian_xingti::before { + content: "\e67b"; +} + +.icon-zhinengguanlian_renlian::before { + content: "\e67c"; +} + +.icon-xiajiantou::before { + content: "\e75c"; +} + +.icon-zhinengguanlian_xiaojiantou::before { + content: "\e67d"; +} + +.icon-zhinengguanlian_jiantou::before { + content: "\e67a"; +} + +.icon-shangjiantou::before { + content: "\e75d"; +} + +.icon-banbenxinxi::before { + content: "\e679"; +} + +.icon-wenhao::before { + content: "\e61f"; +} + +.icon-bianjirenyuan::before { + content: "\e7e0"; +} + +.icon-tishi2::before { + content: "\e7df"; +} + +.icon-shexiangji2::before { + content: "\e7de"; +} + +.icon-guijizhuizong::before { + content: "\e7dd"; +} + +.icon-jiezhen1::before { + content: "\e7dc"; +} + +.icon-tianjiaguijihuisu::before { + content: "\e7db"; +} + +.icon-tingzhi::before { + content: "\e7cd"; +} + +.icon-baoweiquan::before { + content: "\e7ce"; +} + +.icon-shangchuanshipin::before { + content: "\e7d0"; +} + +.icon-yidong::before { + content: "\e7d1"; +} + +.icon-chuangjianxinbukong1::before { + content: "\e7d2"; +} + +.icon-yichu1::before { + content: "\e7d3"; +} + +.icon-tishi1::before { + content: "\e7d4"; +} + +.icon-VS::before { + content: "\e7d5"; +} + +.icon-quanjuzonglan::before { + content: "\e7d6"; +} + +.icon-chakanfenxirenwu1::before { + content: "\e7d7"; +} + +.icon-xiaoxi::before { + content: "\e7d8"; +} + +.icon-yonghuming::before { + content: "\e7d9"; +} + +.icon-tuichu::before { + content: "\e7da"; +} + +.icon-guijizhuizongnor::before { + content: "\e7cb"; +} + +.icon-guijizhuizong2::before { + content: "\e7cc"; +} + +.icon-bukongrenwu1::before { + content: "\e7b7"; +} + +.icon-shexiangji::before { + content: "\e7b8"; +} + +.icon-yujingditu::before { + content: "\e7ba"; +} + +.icon-lixianfenxi2::before { + content: "\e7bb"; +} + +.icon-yuanguanli1::before { + content: "\e7bc"; +} + +.icon-danganku::before { + content: "\e7bd"; +} + +.icon-huisufenxi2::before { + content: "\e7be"; +} + +.icon-kuneijiansuo::before { + content: "\e7bf"; +} + +.icon-jiegouhuachaxun::before { + content: "\e7c0"; +} + +.icon-bukongrenwu2::before { + content: "\e7c2"; +} + +.icon-yuanguanli2::before { + content: "\e7c3"; +} + +.icon-shexiangji1::before { + content: "\e7c4"; +} + +.icon-kuneijiansuo1::before { + content: "\e7c5"; +} + +.icon-lixianfenxi3::before { + content: "\e7c6"; +} + +.icon-danganku1::before { + content: "\e7c7"; +} + +.icon-yujingditu1::before { + content: "\e7c8"; +} + +.icon-huisufenxi3::before { + content: "\e7c9"; +} + +.icon-jiegouhuachaxunnor::before { + content: "\e7ca"; +} + +.icon-chuangjianxinbukong::before { + content: "\e7b6"; +} + +.icon-kuangxuan::before { + content: "\e77f"; +} + +.icon-gaojishaixuan::before { + content: "\e779"; +} + +.icon-gaojishaixuanshouqi::before { + content: "\e77a"; +} + +.icon-bukongrenwu::before { + content: "\e7b5"; +} + +.icon-riqi::before { + content: "\e74f"; +} + +.icon-shijianqiehuan::before { + content: "\e797"; +} + +.icon-shouquan1::before { + content: "\e7b3"; +} + +.icon-video-play::before { + content: "\e653"; +} + +.icon-shishifenxi::before { + content: "\e7af"; +} + +.icon-chakanfenxirenwu::before { + content: "\e7b0"; +} + +.icon-jiegouhuafenxi::before { + content: "\e7ad"; +} + +.icon-tianjiaguiji2::before { + content: "\e6aa"; +} + +.icon-tianjiajiansuomubiao::before { + content: "\e6b0"; +} + +.icon-add::before { + content: "\e661"; +} + +.icon-didian::before { + content: "\e798"; +} + +.icon-bofanghov::before { + content: "\e79f"; +} + +.icon-bofang3::before { + content: "\e7a0"; +} + +.icon-jinggao::before { + content: "\e788"; +} + +.icon-tishi::before { + content: "\e789"; +} + +.icon-bangzhu::before { + content: "\e78a"; +} + +.icon-guanbi1::before { + content: "\e78b"; +} + +.icon-chenggong::before { + content: "\e78c"; +} + +.icon-qianwang::before { + content: "\e7ac"; +} + +.icon-shouquan::before { + content: "\e7ab"; +} + +.icon-jingweidu::before { + content: "\e7aa"; +} + +.icon-shanchu1::before { + content: "\e74e"; +} + +.icon-daochu::before { + content: "\e782"; +} + +.icon-ziyuanguanli::before { + content: "\e7a4"; +} + +.icon-fuwuqishouquan::before { + content: "\e7a5"; +} + +.icon-xiugaimima::before { + content: "\e7a6"; +} + +.icon-zhanghaoguanli::before { + content: "\e7a7"; +} + +.icon-suanlipeie::before { + content: "\e7a8"; +} + +.icon-VMSpeizhi::before { + content: "\e7a9"; +} + +.icon-tianjia1::before { + content: "\e794"; +} + +.icon-yichu::before { + content: "\e795"; +} + +.icon-lujing::before { + content: "\e6cf"; +} + +.icon-jiankongxinxi::before { + content: "\e6c8"; +} + +.icon-fanwei::before { + content: "\e6c9"; +} + +.icon-anfadidian::before { + content: "\e6ca"; +} + +.icon-gongjuxiang::before { + content: "\e6cd"; +} + +.icon-gongjuxiangguanbi1::before { + content: "\e6ce"; +} + +.icon-jiezhen::before { + content: "\e6c2"; +} + +.icon-huisufenxi1::before { + content: "\e6c6"; +} + +.icon-huisufenxi::before { + content: "\e6c7"; +} + +.icon-tianjiashipinwenjian1::before { + content: "\e6c5"; +} + +.icon-jiazaishibai::before { + content: "\e6c3"; +} + +.icon-shuaxin::before { + content: "\e6c4"; +} + +.icon-quanping::before { + content: "\e6c0"; +} + +.icon-quxiaoquanping::before { + content: "\e6c1"; +} + +.icon-shipinbofang::before { + content: "\e6be"; +} + +.icon-shipinzanting::before { + content: "\e6bf"; +} + +.icon-lixianguiji::before { + content: "\e6bd"; +} + +.icon-lixian::before { + content: "\e6bc"; +} + +.icon-xiaojiaobiao::before { + content: "\e6bb"; +} + +.icon-shangchuan1::before { + content: "\e6ba"; +} + +.icon-tianjiaweijiansuoduixiang::before { + content: "\e6b8"; +} + +.icon-tianjiaweijiansuojilu::before { + content: "\e6b9"; +} + +.icon-lixianfenxi1::before { + content: "\e6b7"; +} + +.icon-kuaisujiansuohov::before { + content: "\e6b5"; +} + +.icon-kuaisujiansuo1::before { + content: "\e6b6"; +} + +.icon-kuaisujiansuo::before { + content: "\e6b4"; +} + +.icon-yuanguanli::before { + content: "\e6b1"; +} + +.icon-shexiangtou::before { + content: "\e6b2"; +} + +.icon-lixianfenxi::before { + content: "\e6b3"; +} + +.icon-filter::before { + content: "\e61a"; +} + +.icon-tianjiaweizhuizongduixiang2::before { + content: "\e6af"; +} + +.icon-tianjiaweizhuizongduixiang1::before { + content: "\e6ae"; +} + +.icon-baocun1::before { + content: "\e6a9"; +} + +.icon-tianjiashipinwenjianjia::before { + content: "\e6a5"; +} + +.icon-tianjiashipinwenjian::before { + content: "\e6a6"; +} + +.icon-ditu::before { + content: "\e6a4"; +} + +.icon-xinjianshexiangtou::before { + content: "\e6a3"; +} + +.icon-lishihuisu::before { + content: "\e6a2"; +} + +.icon-decoyitianjiaweiguiji::before { + content: "\e69f"; +} + +.icon-bofangqiehuan::before { + content: "\e6a0"; +} + +.icon-tianjia::before { + content: "\e6a1"; +} + +.icon-baocun::before { + content: "\e698"; +} + +.icon-gongjuxiangguanbi::before { + content: "\e699"; +} + +.icon-shangchuan::before { + content: "\e69b"; +} + +.icon-gongjuxiang1::before { + content: "\e69c"; +} + +.icon-logo::before { + content: "\e692"; +} + +.icon-setting::before { + content: "\e627"; +} + +.icon-user::before { + content: "\e628"; +} + +.icon-quit::before { + content: "\e629"; +} + +.icon-arrowzhankaimeixuanzhong::before { + content: "\e693"; +} + +.icon-arrowzhankaixuanzhong::before { + content: "\e694"; +} + +.icon-xuanzexuanzhong::before { + content: "\e695"; +} + +.icon-xuanzebanxuan::before { + content: "\e696"; +} + +.icon-xuanzenor::before { + content: "\e697"; +} + +.icon-shaixuanguanbinor::before { + content: "\e691"; +} + +.icon-gengduo::before { + content: "\e68e"; +} + +.icon-youzhankai::before { + content: "\e68f"; +} + +.icon-zuoshouqi::before { + content: "\e690"; +} + +.icon-yuan::before { + content: "\e68a"; +} + +.icon-duobianxing::before { + content: "\e68b"; +} + +.icon-fang::before { + content: "\e68c"; +} + +.icon-ceju::before { + content: "\e68d"; +} + +.icon-shishizhuizong1::before { + content: "\e683"; +} + +.icon-guijihuisu1::before { + content: "\e684"; +} + +.icon-tianjiaguiji::before { + content: "\e685"; +} + +.icon-yichuguiji::before { + content: "\e686"; +} + +.icon-fangda::before { + content: "\e680"; +} + +.icon-suoxiao::before { + content: "\e681"; +} + +.icon-xiazai::before { + content: "\e682"; +} + +.icon-fanhui::before { + content: "\e678"; +} + +.icon-sousuo::before { + content: "\e669"; +} + +.icon-quxiaoxuanzhong::before { + content: "\e66a"; +} + +.icon-piliangxuanzenor::before { + content: "\e66b"; +} + +.icon-kaiqifenxi::before { + content: "\e66c"; +} + +.icon-quxiaofenxi::before { + content: "\e66d"; +} + +.icon-shaixuan::before { + content: "\e66e"; +} + +.icon-dangan::before { + content: "\e66f"; +} + +.icon-bofang::before { + content: "\e670"; +} + +.icon-zanting::before { + content: "\e671"; +} + +.icon-shanchu::before { + content: "\e672"; +} + +.icon-tianjiaweizhuizongduixiang::before { + content: "\e673"; +} + +.icon-chakandatu::before { + content: "\e674"; +} + +.icon-jiansuojilu::before { + content: "\e675"; +} + +.icon-yuzhi::before { + content: "\e676"; +} + +.icon-chakanxiangqing::before { + content: "\e677"; +} + +.icon-guijihuisu::before { + content: "\e65c"; +} + +.icon-dianweipeizhinor::before { + content: "\e65d"; +} + +.icon-yirenyidang::before { + content: "\e65e"; +} + +.icon-tongbanfenxi::before { + content: "\e65f"; +} + +.icon-qiehuanzuo::before { + content: "\e662"; +} + +.icon-qiehuanyou::before { + content: "\e663"; +} + +.icon-tingzhidengdai::before { + content: "\e664"; +} + +.icon-yiguanbi::before { + content: "\e665"; +} + +.icon-danchuangguanbi::before { + content: "\e666"; +} + +.icon-lishijilu::before { + content: "\e64a"; +} + +.icon-xuanzhuan::before { + content: "\e648"; +} + +.icon-qingchu::before { + content: "\e649"; +} + +.icon-dangantianjia::before { + content: "\e63d"; +} + +.icon-bianji::before { + content: "\e63e"; +} + +.icon-fullscreen::before { + content: "\e63b"; +} + +.icon-cancle_fullscreen::before { + content: "\e63c"; +} + +.icon-quanyujiansuo_nor::before { + content: "\e639"; +} + +.icon-guijihuisu_nor::before { + content: "\e63a"; +} + diff --git a/packages/meta/es/iconfont/iconfont.js b/packages/meta/es/iconfont/iconfont.js new file mode 100644 index 0000000..6eeb914 --- /dev/null +++ b/packages/meta/es/iconfont/iconfont.js @@ -0,0 +1,43 @@ +window._iconfont_svg_string_1739270 = '', function (h) { + var a = (a = document.getElementsByTagName("script"))[a.length - 1], + l = a.getAttribute("data-injectcss"), + a = a.getAttribute("data-disable-injectsvg"); + if (!a) { + var i, + _c, + o, + t, + z, + v = function v(a, l) { + l.parentNode.insertBefore(a, l); + }; + if (l && !h.__iconfont__svg__cssinject__) { + h.__iconfont__svg__cssinject__ = !0; + try { + document.write(""); + } catch (a) { + console && console.log(a); + } + } + i = function i() { + var a, + l = document.createElement("div"); + l.innerHTML = h._iconfont_svg_string_1739270, (l = l.getElementsByTagName("svg")[0]) && (l.setAttribute("aria-hidden", "true"), l.style.position = "absolute", l.style.width = 0, l.style.height = 0, l.style.overflow = "hidden", l = l, (a = document.body).firstChild ? v(l, a.firstChild) : a.appendChild(l)); + }, document.addEventListener ? ~["complete", "loaded", "interactive"].indexOf(document.readyState) ? setTimeout(i, 0) : (_c = function c() { + document.removeEventListener("DOMContentLoaded", _c, !1), i(); + }, document.addEventListener("DOMContentLoaded", _c, !1)) : document.attachEvent && (o = i, t = h.document, z = !1, p(), t.onreadystatechange = function () { + "complete" == t.readyState && (t.onreadystatechange = null, m()); + }); + } + function m() { + z || (z = !0, o()); + } + function p() { + try { + t.documentElement.doScroll("left"); + } catch (a) { + return void setTimeout(p, 50); + } + m(); + } +}(window); \ No newline at end of file diff --git a/packages/meta/es/iconfont/iconfont.ttf b/packages/meta/es/iconfont/iconfont.ttf new file mode 100644 index 0000000..0043e6a Binary files /dev/null and b/packages/meta/es/iconfont/iconfont.ttf differ diff --git a/packages/meta/es/iconfont/iconfont.woff b/packages/meta/es/iconfont/iconfont.woff new file mode 100644 index 0000000..84f32bb Binary files /dev/null and b/packages/meta/es/iconfont/iconfont.woff differ diff --git a/packages/meta/es/iconfont/iconfont.woff2 b/packages/meta/es/iconfont/iconfont.woff2 new file mode 100644 index 0000000..8173340 Binary files /dev/null and b/packages/meta/es/iconfont/iconfont.woff2 differ diff --git a/packages/meta/es/iconfont/index.d.ts b/packages/meta/es/iconfont/index.d.ts index e769332..fcafc45 100644 --- a/packages/meta/es/iconfont/index.d.ts +++ b/packages/meta/es/iconfont/index.d.ts @@ -1,4 +1,5 @@ import React from 'react'; +import './iconfont.css'; interface IconFontProps { styles?: React.CSSProperties; icon?: string; diff --git a/packages/meta/es/iconfont/index.js b/packages/meta/es/iconfont/index.js index f5914bd..6a980e4 100644 --- a/packages/meta/es/iconfont/index.js +++ b/packages/meta/es/iconfont/index.js @@ -6,6 +6,7 @@ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _ty function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } import React from 'react'; import classNames from 'classnames'; +import "./iconfont.css"; var IconFont = function IconFont(props) { var _ref = props || {}, _ref$title = _ref.title, diff --git a/packages/meta/es/index.d.ts b/packages/meta/es/index.d.ts index 241716b..e0961ce 100644 --- a/packages/meta/es/index.d.ts +++ b/packages/meta/es/index.d.ts @@ -1,3 +1,5 @@ export { default as doubleClick } from './doubleClick'; export { default as Icon } from './iconfont'; -export { default as ImagePreview } from './ImagePreview'; +export { default as CompareImage } from './CompareImage'; +export { default as BigImagePreview } from './BigImagePreview'; +export { default as VideoPlayer } from './VideoPlayer'; diff --git a/packages/meta/es/index.js b/packages/meta/es/index.js index e85eac4..85ebaa1 100644 --- a/packages/meta/es/index.js +++ b/packages/meta/es/index.js @@ -1,3 +1,5 @@ export { default as doubleClick } from "./doubleClick"; export { default as Icon } from "./iconfont"; -export { default as ImagePreview } from "./ImagePreview"; \ No newline at end of file +export { default as CompareImage } from "./CompareImage"; +export { default as BigImagePreview } from "./BigImagePreview"; +export { default as VideoPlayer } from "./VideoPlayer"; \ No newline at end of file diff --git a/packages/meta/es/utils/constants.d.ts b/packages/meta/es/utils/constants.d.ts new file mode 100644 index 0000000..f9bb021 --- /dev/null +++ b/packages/meta/es/utils/constants.d.ts @@ -0,0 +1,12 @@ +export declare const CROP_TYPE: { + CUSTOM: string; + AUTO: string; +}; +export declare const defaultAlignOption: { + points: string[]; + offset: number[]; + overflow: { + adjustX: boolean; + adjustY: boolean; + }; +}; diff --git a/packages/meta/es/utils/constants.js b/packages/meta/es/utils/constants.js new file mode 100644 index 0000000..e2357aa --- /dev/null +++ b/packages/meta/es/utils/constants.js @@ -0,0 +1,12 @@ +export var CROP_TYPE = { + CUSTOM: 'CSUTOM', + AUTO: 'AUTO' +}; +export var defaultAlignOption = { + points: ['bl', 'br'], + offset: [6, 0], + overflow: { + adjustX: true, + adjustY: true + } +}; \ No newline at end of file diff --git a/packages/meta/lib/BigImagePreview/BigImagePreview.d.ts b/packages/meta/lib/BigImagePreview/BigImagePreview.d.ts new file mode 100644 index 0000000..45d7836 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/BigImagePreview.d.ts @@ -0,0 +1,35 @@ +import React, { ReactElement } from 'react'; +import { type Rect, type IScreenshotButtonProp, type AlignType, type ViewOption, type IOdRectOrigin } from '@zhst/types'; +import './index.less'; +export interface ImgViewProps extends React.HTMLAttributes { + dataSource: Array<{ + url?: string; + imageKey: string; + attachImg?: Array<{ + label: string; + url: string; + }>; + odRect?: Rect; + score?: number; + showScore?: boolean; + cameraPosition?: string; + time?: string | number; + objects: any[]; + }>; + showAttachImgLabel: boolean; + showOpt: boolean; + width?: string | number; + height?: string | number; + screenshotButtonAlign: AlignType; + screenshotButtonRender: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; + hideLeftTopBtn?: boolean; + showScore?: boolean; + viewOption?: ViewOption; + objects: IOdRectOrigin[]; +} +export interface ImgViewRef { + imgInsRef: React.MutableRefObject; + setShowCrop: React.Dispatch>; +} +export declare const BigImagePreview: React.ForwardRefExoticComponent>; +export default BigImagePreview; diff --git a/packages/meta/lib/BigImagePreview/BigImagePreview.js b/packages/meta/lib/BigImagePreview/BigImagePreview.js new file mode 100644 index 0000000..af9f764 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/BigImagePreview.js @@ -0,0 +1,487 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImagePreview/BigImagePreview.tsx +var BigImagePreview_exports = {}; +__export(BigImagePreview_exports, { + BigImagePreview: () => BigImagePreview, + default: () => BigImagePreview_default +}); +module.exports = __toCommonJS(BigImagePreview_exports); +var import_react = __toESM(require("react")); +var import_classnames = __toESM(require("classnames")); +var import_hooks = require("@zhst/hooks"); +var import_func = require("@zhst/func"); +var import_rc_align = __toESM(require("rc-align")); +var import_antd = require("antd"); +var import_iconfont = __toESM(require("../iconfont")); +var import_ImageEditor = require("../ImageEditor"); +var import_BtnGroup = __toESM(require("./components/BtnGroup")); +var import_index = require("./index.less"); +var import_ScreenhotButtons = __toESM(require("./components/ScreenhotButtons")); +var import_constants = require("../utils/constants"); +var componentName = `zhst-image__img-view`; +var cropBtnDataSource = [ + { + key: "close", + icon: "icon-danchuangguanbi", + title: "退出" + }, + { + key: "autoCrop", + icon: "icon-zidong", + title: "智能框选" + }, + { + key: "customCrop", + icon: "icon-shoudong", + title: "手动框选" + } +]; +var operateBtnDataSource = [ + { + key: "zoomOut", + icon: "icon-fangda", + title: "放大" + }, + { + key: "zoomIn", + icon: "icon-suoxiao", + title: "缩小" + }, + { + key: "reset", + icon: "icon-zhongzhi3", + title: "重置图片" + } +]; +var BigImagePreview = import_react.default.forwardRef((props, ref) => { + var _a, _b; + const { + dataSource = [], + width, + height, + showScore = true, + objects = [], + showOpt = false, + showAttachImgLabel = true, + screenshotButtonAlign = import_constants.defaultAlignOption, + screenshotButtonRender = (0, import_ScreenhotButtons.default)({ + onBigImageActionClick: () => { + }, + disableBtn: [] + }), + hideLeftTopBtn = true, + viewOption = {} + } = props; + const imgContainerRef = import_react.default.useRef(null); + const [isReady, setIsReady] = (0, import_react.useState)(false); + const [currentIndex, setCurrentIndex] = (0, import_react.useState)(0); + console.log("props", props); + const init = (0, import_react.useCallback)(($container) => { + imgContainerRef.current = $container; + setIsReady(true); + }, []); + const imgInsRef = (0, import_react.useRef)(null); + const [isImgReady, setIsImgReady] = (0, import_react.useState)(false); + (0, import_react.useEffect)(() => { + var _a2; + console.log("123", 123); + if (!isReady || !(imgContainerRef == null ? void 0 : imgContainerRef.current)) + return; + const handleReady = (0, import_func.addEventListenerWrapper)(imgContainerRef.current, import_ImageEditor.EVENT_VIEWER_READY, () => { + setIsImgReady(true); + }); + const handleTransformChange = (0, import_func.addEventListenerWrapper)( + imgContainerRef.current, + import_ImageEditor.EVENT_VIEWER_TRANSFORM_CHANGE, + () => { + } + ); + imgInsRef.current = new import_ImageEditor.Viewer(imgContainerRef.current, { + ...viewOption, + fitScaleAsMinScale: true, + image: (0, import_func.generateImg)((_a2 = dataSource[currentIndex]) == null ? void 0 : _a2.imageKey) + }); + return () => { + var _a3, _b2; + handleReady == null ? void 0 : handleReady.remove(); + handleTransformChange == null ? void 0 : handleTransformChange.remove(); + (_b2 = (_a3 = imgInsRef == null ? void 0 : imgInsRef.current) == null ? void 0 : _a3.destroy) == null ? void 0 : _b2.call(_a3); + imgInsRef.current = null; + }; + }, [isReady, currentIndex]); + const handleOptClick = (v) => { + var _a2, _b2, _c, _d, _e, _f; + switch (v) { + case "zoomOut": + (_b2 = (_a2 = imgInsRef == null ? void 0 : imgInsRef.current) == null ? void 0 : _a2.scaleTo) == null ? void 0 : _b2.call(_a2, 0.1); + break; + case "zoomIn": + (_d = (_c = imgInsRef == null ? void 0 : imgInsRef.current) == null ? void 0 : _c.scaleTo) == null ? void 0 : _d.call(_c, -0.1); + break; + case "reset": + (_f = (_e = imgInsRef == null ? void 0 : imgInsRef.current) == null ? void 0 : _e.reset) == null ? void 0 : _f.call(_e, -0.1); + break; + } + }; + const cropInsRef = (0, import_react.useRef)(null); + const [showCrop, setShowCrop] = (0, import_react.useState)(showOpt); + const [cropType, setCropType] = (0, import_react.useState)(import_constants.CROP_TYPE["AUTO"]); + const [odList, setOdList] = (0, import_react.useState)([]); + const [extendOdList, setExtendOdList] = (0, import_react.useState)([]); + const [selectRectId, setSelectRectId] = (0, import_react.useState)(null); + const alginContainerRef = (0, import_react.useRef)(null); + const alignRef = (0, import_react.useRef)(null); + const [cropRect, setCropRect] = (0, import_react.useState)(null); + const [selectAlgorithmVersion, setSelectAlgorithmVersion] = (0, import_react.useState)(null); + const handlerCropStartRef = (0, import_react.useRef)(null); + const handlerCropEndRef = (0, import_react.useRef)(null); + const handleShapeSelectRef = (0, import_react.useRef)(null); + (0, import_react.useEffect)(() => { + initData(dataSource[currentIndex].objects || objects); + return () => { + var _a2, _b2, _c, _d, _e, _f, _g; + (_b2 = (_a2 = imgInsRef.current) == null ? void 0 : _a2.clearShape) == null ? void 0 : _b2.call(_a2); + (_c = handlerCropStartRef.current) == null ? void 0 : _c.remove(); + (_d = handlerCropEndRef.current) == null ? void 0 : _d.remove(); + (_e = handleShapeSelectRef.current) == null ? void 0 : _e.remove(); + (_g = (_f = cropInsRef == null ? void 0 : cropInsRef.current) == null ? void 0 : _f.destroy) == null ? void 0 : _g.call(_f); + cropInsRef.current = null; + }; + }, [isImgReady, showCrop, cropType, currentIndex]); + const initData = (_objects) => { + var _a2, _b2; + const imgIns = imgInsRef.current; + const _odRect = dataSource[currentIndex].odRect; + setCropRect(null); + if (!isImgReady) + return; + if (!showCrop) { + (_a2 = imgIns == null ? void 0 : imgIns.addShape) == null ? void 0 : _a2.call(imgIns, { + x: (0, import_func.get)(_odRect, "x", 0), + y: (0, import_func.get)(_odRect, "y", 0), + w: (0, import_func.get)(_odRect, "w", 0), + h: (0, import_func.get)(_odRect, "h", 0), + selectAble: false + }); + return; + } + if (cropType === import_constants.CROP_TYPE["AUTO"]) { + const handleGetOD = (odList2) => { + const imgSize = imgIns.getImgSize(); + const shapeList = odList2.map((rect2) => ({ + ...rect2, + selectAble: true, + id: rect2["id"], + algorithmVersion: rect2.algorithmVersion + })); + imgIns.replaceShape(shapeList); + const extendRect = shapeList.map((rect2) => { + const _extendRect = (0, import_func.getExtendRect)(rect2, imgSize.w, imgSize.h, rect2.algorithmVersion); + return { ...rect2, ..._extendRect }; + }); + setExtendOdList(extendRect); + imgIns.replaceShape(shapeList); + handleShapeSelectRef.current = (0, import_func.addEventListenerWrapper)(imgContainerRef.current, "shape-select", (e) => { + const id = e.detail; + setSelectRectId(id); + const selectShape = shapeList.find((v) => v["id"] === id); + if (selectShape) { + setSelectAlgorithmVersion(selectShape["algorithmVersion"]); + const axisRect = imgIns.imgRectAxisToCanvasAxisRect(selectShape); + const rect2 = { + x: axisRect.x2 > axisRect.x ? axisRect.x : axisRect.x2, + y: axisRect.y2 > axisRect.y ? axisRect.y : axisRect.y2, + w: Math.abs(axisRect.x2 - axisRect.x), + h: Math.abs(axisRect.y2 - axisRect.y) + }; + setCropRect(rect2); + } else { + setCropRect(null); + } + }); + }; + const rect = (0, import_func.getOdRect)({ objects: _objects }); + setOdList(rect); + handleGetOD(rect); + } + if (cropType === import_constants.CROP_TYPE["CUSTOM"]) { + (_b2 = imgIns == null ? void 0 : imgIns.clearShape) == null ? void 0 : _b2.call(imgIns); + handlerCropStartRef.current = (0, import_func.addEventListenerWrapper)(imgContainerRef.current, import_ImageEditor.EVENT_CROP_START, () => { + setSelectAlgorithmVersion(null); + setCropRect(null); + }); + handlerCropEndRef.current = (0, import_func.addEventListenerWrapper)(imgContainerRef.current, import_ImageEditor.EVENT_CROP_END, (event) => { + var _a3, _b3; + const data = event.detail; + setSelectAlgorithmVersion(null); + setCropRect({ + x: data.left, + y: data.top, + w: data.width, + h: data.height + }); + (_b3 = (_a3 = alignRef == null ? void 0 : alignRef.current) == null ? void 0 : _a3.forceAlign) == null ? void 0 : _b3.call(_a3); + }); + cropInsRef.current = new import_ImageEditor.Cropper(imgContainerRef.current, { + showMask: true, + viewer: imgIns + }); + } + }; + const latestCropType = (0, import_hooks.useLatest)(cropType); + const latestImgKey = (0, import_hooks.useLatest)(dataSource[currentIndex].imageKey); + const latestCropRect = (0, import_hooks.useLatest)(cropRect); + const getCropInfo = async () => { + const cropType2 = latestCropType.current; + const cropRect2 = latestCropRect.current; + const imgIns = imgInsRef.current; + const transform = imgIns.targetTransform; + let newImgKey = latestImgKey.current; + let rectList = []; + let extendRectList = []; + let selectIndex = 0; + switch (cropType2) { + case import_constants.CROP_TYPE["AUTO"]: + const shapes = imgIns.getSelectShape(); + const shapeIds = shapes.map((v) => v["id"]); + rectList = odList.filter((v) => shapeIds.includes(v["id"])).map((item) => { + if (item.algorithmVersion === "OBJECT_TYPE_FACE" || item.objectType === "OBJECT_TYPE_FACE") { + if (!(0, import_func.isNull)(item.extendBox)) { + return { + ...item, + w: (0, import_func.get)(item, "extendBox.w"), + h: (0, import_func.get)(item, "extendBox.h"), + x: (0, import_func.get)(item, "extendBox.x"), + y: (0, import_func.get)(item, "extendBox.y") + }; + } + } else { + return item; + } + }); + extendRectList = extendOdList.filter((v) => shapeIds.includes(v["id"])).map((v) => (0, import_func.pick)(v, ["x", "y", "w", "h", "algorithmVersion", "id"])); + selectIndex = rectList.findIndex((v) => v["id"] === selectRectId); + break; + default: + const newRect = (0, import_func.getTransformRect)(imgIns.image, transform, cropRect2); + if ((0, import_func.get)(transform, "rotate", 0) % 360 != 0) { + const data = (0, import_func.getRotateImg)(imgIns.image, (0, import_func.get)(transform, "rotate", 0)); + newImgKey = await (0, import_func.upload)(data); + } + rectList.push(newRect); + extendRectList.push(newRect); + break; + } + await Promise.all( + extendRectList.map(async (rect, index) => { + const file = await (0, import_func.getFileByRect)(imgIns.image, rect); + const imgKey = await (0, import_func.upload)(file); + extendRectList[index] = { ...rect, imgKey }; + }) + ); + await Promise.all( + rectList.map(async (rect, index) => { + const faceCorrectImage = rect["faceCorrectImage"]; + let faceCorrectImageKey; + if (faceCorrectImage) { + const base64 = `data:image/jpg;base64,${faceCorrectImage}`; + const blobData = (0, import_func.dataURLToBlob)(base64); + const file = new window.File([blobData], `${(/* @__PURE__ */ new Date()).getTime()}`); + faceCorrectImageKey = await (0, import_func.upload)(file); + } + const newRect = { + ...rect, + ...faceCorrectImageKey ? { faceCorrectImageKey } : {} + }; + delete newRect["faceCorrectImage"]; + rectList[index] = newRect; + }) + ); + return { rectList, extendRectList, selectIndex, imgKey: newImgKey }; + }; + const handleCropBtnClick = (v) => { + switch (v) { + case "close": + setShowCrop(false); + break; + case "autoCrop": + setCropType(import_constants.CROP_TYPE["AUTO"]); + break; + case "customCrop": + setCropType(import_constants.CROP_TYPE["CUSTOM"]); + break; + } + }; + const [selectAttachImgIndex, setSelectAttachImgIndex] = (0, import_react.useState)(0); + const [isZoomin, setIsZoomin] = (0, import_react.useState)(false); + const handleChangeIndex = (diff) => { + var _a2; + const _index = currentIndex + diff; + if (!((_a2 = dataSource == null ? void 0 : dataSource[_index]) == null ? void 0 : _a2.imageKey)) + return; + setCurrentIndex(_index); + }; + (0, import_react.useImperativeHandle)(ref, () => ({ + imgInsRef, + setShowCrop, + initData, + getCropInfo, + handleChangeIndex + })); + return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}`), style: { height, width } }, dataSource.length ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)( + `${componentName}-main`, + cropType === import_constants.CROP_TYPE["AUTO"] && `${componentName}-main--cursor` + ), + ref: init + } + ), !hideLeftTopBtn && /* @__PURE__ */ import_react.default.createElement( + import_BtnGroup.default, + { + className: (0, import_classnames.default)(`${componentName}-opt`), + dataSource: operateBtnDataSource, + onClick: handleOptClick, + placement: "left" + } + ), showCrop && /* @__PURE__ */ import_react.default.createElement( + import_BtnGroup.default, + { + circle: true, + className: (0, import_classnames.default)(`${componentName}-crop-opt`), + dataSource: cropBtnDataSource, + onClick: handleCropBtnClick, + selectKey: cropType === import_constants.CROP_TYPE["AUTO"] ? "autoCrop" : "customCrop" + } + ), showCrop && cropRect && screenshotButtonRender && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( + "div", + { + ref: alginContainerRef, + className: (0, import_classnames.default)(`${componentName}-align`), + style: Object.assign( + { + width: cropRect.w, + height: cropRect.h + }, + (0, import_func.getTransforms)({ + translateX: cropRect.x, + translateY: cropRect.y + }) + ) + } + ), /* @__PURE__ */ import_react.default.createElement( + import_rc_align.default, + { + ref: alignRef, + monitorWindowResize: true, + align: screenshotButtonAlign, + target: function() { + return alginContainerRef.current; + } + }, + screenshotButtonRender({ + model: "IMAGE", + getCropInfo, + setShowCrop, + cropType, + selectAlgorithmVersion + }) + )), ((_a = dataSource[currentIndex].attachImg) == null ? void 0 : _a.length) && !showCrop && /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)( + `${componentName}-attach`, + isZoomin && `${componentName}-attach--zoomin`, + `${componentName}-attach--fixed`, + isZoomin && `${componentName}-attach--zoomin--fixed` + ) + }, + /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}-attach__tab`) }, showAttachImgLabel ? (_b = dataSource[currentIndex].attachImg) == null ? void 0 : _b.map(({ label }, index) => /* @__PURE__ */ import_react.default.createElement( + "div", + { + key: index, + className: (0, import_classnames.default)( + `${componentName}-attach__tab-item`, + selectAttachImgIndex === index && `${componentName}-attach__tab-item--select` + ), + onMouseEnter: () => { + setSelectAttachImgIndex(index); + } + }, + label + )) : null), + /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}-attach__scale`) }, /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onMouseDown: (e) => { + if (e.button == 0) { + setIsZoomin((pre) => !pre); + } + }, + style: { + color: "#fff" + } + }, + /* @__PURE__ */ import_react.default.createElement( + import_iconfont.default, + { + styles: { display: "flex" }, + icon: isZoomin ? "icon-cancle_fullscreen" : "icon-fullscreen" + } + ) + )), + /* @__PURE__ */ import_react.default.createElement( + "img", + { + draggable: "false", + className: (0, import_classnames.default)( + `${componentName}-attach__img`, + `${componentName}-attach__img--fixed` + ), + src: (0, import_func.get)(dataSource[currentIndex].attachImg, `${selectAttachImgIndex}.url`, "") + } + ) + ), showScore && /* @__PURE__ */ import_react.default.createElement( + "div", + { + style: { bottom: 20 }, + className: (0, import_classnames.default)(`${componentName}__face-score`) + }, + `人脸质量分:${Number(dataSource[currentIndex].score).toFixed(2)}` + )) : /* @__PURE__ */ import_react.default.createElement(import_antd.Empty, { image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE, description: "暂无数据" })); +}); +BigImagePreview.displayName = "BigImagePreview"; +var BigImagePreview_default = BigImagePreview; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BigImagePreview +}); diff --git a/packages/meta/es/ImagePreview/components/CornerScore/index.less b/packages/meta/lib/BigImagePreview/bigImagePreviewHelper.d.ts similarity index 100% rename from packages/meta/es/ImagePreview/components/CornerScore/index.less rename to packages/meta/lib/BigImagePreview/bigImagePreviewHelper.d.ts diff --git a/packages/meta/lib/ImagePreview/components/CornerScore/index.less b/packages/meta/lib/BigImagePreview/bigImagePreviewHelper.js similarity index 100% rename from packages/meta/lib/ImagePreview/components/CornerScore/index.less rename to packages/meta/lib/BigImagePreview/bigImagePreviewHelper.js diff --git a/packages/meta/lib/BigImagePreview/components/BtnGroup/index.d.ts b/packages/meta/lib/BigImagePreview/components/BtnGroup/index.d.ts new file mode 100644 index 0000000..960a037 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/components/BtnGroup/index.d.ts @@ -0,0 +1,17 @@ +import React, { MouseEvent } from 'react'; +import { TooltipProps } from 'antd'; +import './index.less'; +export interface BtnGroupProps { + className: string; + dataSource: Array<{ + key: string; + icon: string; + title: string; + }>; + onClick: (v: string, e: MouseEvent) => void; + selectKey?: string; + circle?: boolean; + placement?: TooltipProps['placement']; +} +export declare const BtnGroup: React.FC; +export default BtnGroup; diff --git a/packages/meta/lib/BigImagePreview/components/BtnGroup/index.js b/packages/meta/lib/BigImagePreview/components/BtnGroup/index.js new file mode 100644 index 0000000..8413f3f --- /dev/null +++ b/packages/meta/lib/BigImagePreview/components/BtnGroup/index.js @@ -0,0 +1,83 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImagePreview/components/BtnGroup/index.tsx +var BtnGroup_exports = {}; +__export(BtnGroup_exports, { + BtnGroup: () => BtnGroup, + default: () => BtnGroup_default +}); +module.exports = __toCommonJS(BtnGroup_exports); +var import_react = __toESM(require("react")); +var import_classnames = __toESM(require("classnames")); +var import_antd = require("antd"); +var import_iconfont = __toESM(require("../../../iconfont")); +var import_index = require("./index.less"); +var componentName = `zhst-image__btn-group`; +var BtnGroup = (props) => { + const { dataSource, onClick, className, circle, selectKey = "", placement = "right" } = props; + return /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)( + componentName, + circle && `${componentName}--circle`, + className + ) + }, + dataSource.map(({ key, icon, title }) => { + const isSelect = key === selectKey; + return /* @__PURE__ */ import_react.default.createElement(import_antd.Tooltip, { key, placement, title }, /* @__PURE__ */ import_react.default.createElement( + "div", + { + key, + className: (0, import_classnames.default)( + `${componentName}__item`, + isSelect && `${componentName}__item--active` + ) + }, + /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: (e) => { + onClick(key, e); + } + }, + /* @__PURE__ */ import_react.default.createElement(import_iconfont.default, { size: 18, icon }) + ) + )); + }) + ); +}; +BtnGroup.displayName = "BtnGroup"; +var BtnGroup_default = BtnGroup; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BtnGroup +}); diff --git a/packages/meta/lib/BigImagePreview/components/BtnGroup/index.less b/packages/meta/lib/BigImagePreview/components/BtnGroup/index.less new file mode 100644 index 0000000..db03187 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/components/BtnGroup/index.less @@ -0,0 +1,51 @@ +.zhst-image__btn-group { + // display: flex; + width: 30px; + box-shadow: 0 2px 6px 0 rgb(0 0 0 / 40%); + + &__item { + display: flex; + width: 30px; + height: 30px; + align-items: center; + justify-content: center; + background: #000; + + &>button { + padding: 0; + color: #fff; + + &:hover { + color: #09f; + } + + &:active { + color: #09f; + } + + &:focus { + color: #fff; + } + + &>span { + display: flex; + } + } + + &--active { + &>button { + color: #09f; + } + } + } + + &--circle { + background-color: none; + box-shadow: none; + } + + &--circle &__item { + margin-bottom: 4px; + border-radius: 50%; + } +} diff --git a/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.d.ts b/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.d.ts new file mode 100644 index 0000000..cb09279 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.d.ts @@ -0,0 +1,14 @@ +import React from 'react'; +import type { AlgorithmVersion } from '@zhst/types'; +import './index.less'; +interface IScreenShotButton { + getCropInfo: () => void; + setShowCrop: any; + cropType: string; + selectAlgorithmVersion?: AlgorithmVersion | null; +} +declare const getScreenshotButtonRender: (arg: { + disableBtn: number[]; + onBigImageActionClick: (type: number, item: any) => void; +}) => (param: IScreenShotButton) => React.JSX.Element; +export default getScreenshotButtonRender; diff --git a/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.js b/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.js new file mode 100644 index 0000000..d39af2e --- /dev/null +++ b/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.js @@ -0,0 +1,126 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImagePreview/components/ScreenhotButtons/index.tsx +var ScreenhotButtons_exports = {}; +__export(ScreenhotButtons_exports, { + default: () => ScreenhotButtons_default +}); +module.exports = __toCommonJS(ScreenhotButtons_exports); +var import_react = __toESM(require("react")); +var import_antd = require("antd"); +var import_classnames = __toESM(require("classnames")); +var import_BigImageModal = require("@zhst/types/BigImageModal"); +var import_index = require("./index.less"); +var componentName = "bigImageWrapper--v2"; +var getScreenshotButtonRender = (arg) => { + const { disableBtn = [], onBigImageActionClick } = arg; + return (param) => { + const { getCropInfo, setShowCrop, cropType, selectAlgorithmVersion } = param; + let isAuto = cropType === "AUTO"; + return /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)(`${componentName}__screenshot`), + style: { + zIndex: 100, + position: "absolute", + width: "86px" + } + }, + !disableBtn.includes(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP"]) && isAuto && /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: async (e) => { + e.stopPropagation(); + const image = await getCropInfo(); + setShowCrop(false); + onBigImageActionClick(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP"], image); + } + }, + "目标检索" + ), + !disableBtn.includes(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP_BODY"]) && !isAuto && /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: async (e) => { + e.stopPropagation(); + const image = await getCropInfo(); + setShowCrop(false); + onBigImageActionClick(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP_BODY"], image); + } + }, + "搜形体" + ), + !disableBtn.includes(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP_VEHICLE"]) && !isAuto && /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: async (e) => { + e.stopPropagation(); + const image = await getCropInfo(); + setShowCrop(false); + onBigImageActionClick(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP_VEHICLE"], image); + } + }, + "搜非机动车" + ), + !disableBtn.includes(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP_ARCHIVE"]) && selectAlgorithmVersion !== 0 && /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: (e) => { + e.stopPropagation(); + let image = getCropInfo(); + setShowCrop(false); + if (!image.rectList[0].algorithmVersion) { + image.rectList[0].algorithmVersion = 0; + image.extendRectList[0].algorithmVersion = 0; + } + onBigImageActionClick(import_BigImageModal.IBigImageOpt["ADD_HISTORY_WITH_CROP_ARCHIVE"], image); + } + }, + "档案检索" + ), + /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: (e) => { + e.stopPropagation(); + setShowCrop(false); + } + }, + "退出框选" + ) + ); + }; +}; +var ScreenhotButtons_default = getScreenshotButtonRender; diff --git a/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.less b/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.less new file mode 100644 index 0000000..ca407fa --- /dev/null +++ b/packages/meta/lib/BigImagePreview/components/ScreenhotButtons/index.less @@ -0,0 +1,21 @@ +.bigImageWrapper--v2__screenshot { + min-width: 90px; + background: rgb(0 0 0 / 50%); + border-radius: 0; + + &>button { + width: 100%; + color: #fff !important; + font-family: 'Microsoft YaHei'; + font-size: 12px !important; + border-radius: 0; + + &>span { + color: #fff; + } + + &:hover { + background-color: #09f !important; + } + } +} diff --git a/packages/meta/lib/BigImagePreview/index.d.ts b/packages/meta/lib/BigImagePreview/index.d.ts new file mode 100644 index 0000000..7469634 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/index.d.ts @@ -0,0 +1,3 @@ +import BigImagePreview from './BigImagePreview'; +export type { ImgViewProps } from './BigImagePreview'; +export default BigImagePreview; diff --git a/packages/meta/lib/BigImagePreview/index.js b/packages/meta/lib/BigImagePreview/index.js new file mode 100644 index 0000000..3944af4 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/index.js @@ -0,0 +1,36 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/BigImagePreview/index.tsx +var BigImagePreview_exports = {}; +__export(BigImagePreview_exports, { + default: () => BigImagePreview_default +}); +module.exports = __toCommonJS(BigImagePreview_exports); +var import_BigImagePreview = __toESM(require("./BigImagePreview")); +var BigImagePreview_default = import_BigImagePreview.default; diff --git a/packages/meta/lib/BigImagePreview/index.less b/packages/meta/lib/BigImagePreview/index.less new file mode 100644 index 0000000..d192880 --- /dev/null +++ b/packages/meta/lib/BigImagePreview/index.less @@ -0,0 +1,123 @@ +.zhst-image__img-view { + position: relative; + width: calc(100%); + height: 100%; + + &__face-score { + position: absolute; + right: 20px; + bottom: 80px; + color: red; + font-family: 'Microsoft YaHei'; + font-size: 19px; + font-weight: bold; + } + + &-opt { + position: absolute; + z-index: 99; + top: 0; + } + + &-crop-opt { + position: absolute; + z-index: 99; + top: 0; + right: 0; + } + + &-align { + position: absolute; + top: 0; + left: 0; + pointer-events: none; + } + + &-main { + width: 100%; + height: 100%; + font-size: 0; + + &--cursor { + & canvas { + min-height: 320px; + cursor: pointer; + } + } + } + + &-screenshot { + position: absolute; + z-index: 10; + } + + &-attach { + position: absolute; + z-index: 11; + bottom: 0; + + // left: 78px; + left: 0; + min-width: 120px; + height: 202px; + transition: all 200ms; + + &--zoomin { + height: 100%; + } + + &__tab { + position: absolute; + top: 0; + left: 0; + display: flex; + + &-item { + display: flex; + width: 30px; + height: 24px; + align-items: center; + justify-content: center; + background: #000; + color: #fff; + cursor: pointer; + font-size: 12px; + opacity: 0.5; + transition: all 200ms; + + &--select { + width: 48px; + height: 34px; + background: #09f; + opacity: 1; + } + } + } + + &__scale { + position: absolute; + top: 4px; + right: 4px; + display: flex; + width: 30px; + height: 30px; + align-items: center; + justify-content: center; + background: rgb(0 0 0 / 60%); + border-radius: 100%; + cursor: pointer; + line-height: 30px; + text-align: center; + } + + &__img { + height: 100%; + object-fit: contain; + + &--fixed { + width: 100%; + object-fit: contain; + } + } + } +} diff --git a/packages/meta/lib/CompareImage/CompareImage.d.ts b/packages/meta/lib/CompareImage/CompareImage.d.ts new file mode 100644 index 0000000..18fbaca --- /dev/null +++ b/packages/meta/lib/CompareImage/CompareImage.d.ts @@ -0,0 +1,20 @@ +import React from 'react'; +import './index.less'; +export interface CompareImageProps { + /** + * @description 属性描述 + * @default "默认值" + */ + label: string; + openRoll?: boolean; + dataSource?: Array<{ + url: string; + score: number; + }>; + showScore?: boolean; + current: number; +} +export interface CompareImageRefProps { +} +declare const CompareImage: React.ForwardRefExoticComponent>; +export default CompareImage; diff --git a/packages/meta/lib/ImagePreview/index.js b/packages/meta/lib/CompareImage/CompareImage.js similarity index 79% rename from packages/meta/lib/ImagePreview/index.js rename to packages/meta/lib/CompareImage/CompareImage.js index 79d5a26..78f4153 100644 --- a/packages/meta/lib/ImagePreview/index.js +++ b/packages/meta/lib/CompareImage/CompareImage.js @@ -26,12 +26,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/ImagePreview/index.tsx -var ImagePreview_exports = {}; -__export(ImagePreview_exports, { - default: () => ImagePreview_default +// src/CompareImage/CompareImage.tsx +var CompareImage_exports = {}; +__export(CompareImage_exports, { + default: () => CompareImage_default }); -module.exports = __toCommonJS(ImagePreview_exports); +module.exports = __toCommonJS(CompareImage_exports); var import_react = __toESM(require("react")); var import_func = require("@zhst/func"); var import_hooks = require("@zhst/hooks"); @@ -40,25 +40,16 @@ var import_classnames = __toESM(require("classnames")); var import_viewer = __toESM(require("../ImageEditor/viewer")); var import_iconfont = __toESM(require("../iconfont")); var import_CornerScore = __toESM(require("./components/CornerScore")); +var import_index = require("./index.less"); var componentName = `zhst-image__compater-view`; -var CompaterImage = (props) => { - const { url, label, openRoll = false, urls = [], score } = props; +var CompareImage = (0, import_react.forwardRef)((props, ref) => { + const { label, openRoll = false, dataSource = [], showScore = true, current = 0 } = props; const imgContainerRef = (0, import_react.useRef)(null); const imgInsRef = (0, import_react.useRef)(null); const [scale, setScale] = (0, import_react.useState)(0); - const [showUrl, setShowUrl] = (0, import_react.useState)((0, import_func.generateImg)(url)); - (0, import_hooks.useUpdateEffect)(() => { - var _a; - setShowUrl((0, import_func.generateImg)(url)); - if (imgInsRef.current) { - (_a = imgInsRef.current) == null ? void 0 : _a.refleshImage({ - image: (0, import_func.generateImg)(url) - }); - } - }, [url]); + const [currentIndex, setCurrentIndex] = (0, import_react.useState)(current); (0, import_react.useEffect)(() => { - setShowUrl(url); - const handleTransformChange = (0, import_func.addEventListener)( + const handleTransformChange = (0, import_func.addEventListenerWrapper)( imgContainerRef.current, "viewer-transform-change", (event) => { @@ -66,9 +57,11 @@ var CompaterImage = (props) => { setScale((0, import_func.get)(data, "scale", 0)); } ); - imgInsRef.current = new import_viewer.default(imgContainerRef.current, { - image: (0, import_func.generateImg)(url) - }); + if ((0, import_func.generateImg)(dataSource[currentIndex].url)) { + imgInsRef.current = new import_viewer.default(imgContainerRef.current, { + image: (0, import_func.generateImg)(dataSource[currentIndex].url) + }); + } return () => { var _a, _b; handleTransformChange == null ? void 0 : handleTransformChange.remove(); @@ -76,42 +69,42 @@ var CompaterImage = (props) => { imgInsRef.current = null; }; }, []); - const handlePre = (0, import_react.useCallback)(() => { + (0, import_hooks.useUpdateEffect)(() => { var _a; - const index = urls.findIndex((v) => v === showUrl); - if (index > 0) { - const newUrl = urls[index - 1]; - setShowUrl(newUrl); + if (imgInsRef.current) { (_a = imgInsRef.current) == null ? void 0 : _a.refleshImage({ - image: newUrl + image: (0, import_func.generateImg)(dataSource[currentIndex].url) }); } - }, [showUrl, urls]); - const handleNext = (0, import_react.useCallback)(() => { - var _a; - const index = urls.findIndex((v) => v === showUrl); - if (index >= 0 && !!urls[index + 1]) { - const newUrl = urls[index + 1]; - setShowUrl(newUrl); - (_a = imgInsRef.current) == null ? void 0 : _a.refleshImage({ - image: newUrl - }); - } - }, [showUrl, urls]); - return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__container`) }, /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__label`) }, label), /* @__PURE__ */ import_react.default.createElement("div", { ref: imgContainerRef, className: (0, import_classnames.default)(`${componentName}__view`) }), !url && /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__empty`) }, /* @__PURE__ */ import_react.default.createElement( + }, [currentIndex]); + const handleIndexChange = (changeVal) => { + var _a, _b; + const _index = currentIndex + changeVal; + if (!((_a = dataSource == null ? void 0 : dataSource[_index]) == null ? void 0 : _a.url)) + return; + (_b = imgInsRef.current) == null ? void 0 : _b.refleshImage({ + image: (0, import_func.generateImg)(dataSource[_index].url) + }); + setCurrentIndex(_index); + }; + (0, import_react.useImperativeHandle)(ref, () => ({ + imgInsRef, + handleIndexChange + })); + return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__container`) }, /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__label`) }, label), /* @__PURE__ */ import_react.default.createElement("div", { ref: imgContainerRef, className: (0, import_classnames.default)(`${componentName}__view`) }), !dataSource.length && /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__empty`) }, /* @__PURE__ */ import_react.default.createElement( "img", { src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANkupk+ACNPvkSPcAAEibACyXUyfABGm3yNHuAECRNgAZLuYPgEirKlHu7u7XdyytGwHAd8jjNyng4OD7vnz51dbPT8/7z58+NB9+/bt6jU/TI+AGWHEnrx48eJ/EsSmHzx40L18+fLyzxF3ZVMjEyDCiEDjMYZZS5wiPXnyZFbJaxMhQIQRGzHvWR7XCyOCXsOmiDAi1HmPMMQjDpbpEiDCiL358eNHurW/5SnWdIBbXiDCiA38/Pnzrce2YyZ4//59F3ePLNMl4PbpiL2J0L979+7yDtHDhw8vtzzvdGnEXdvUigSIsCLAWavHp/+qM0BcXMd/q25n1vF57TYBp0a3mUzilePj4+7k5KSLb6gt6ydAhPUzXnoPR0dHl79WGTNCfBnn1uvSCJdegQhLI1vvCk+fPu2ePXt2tZOYEV6/fn31dz+shwAR1sP1cqvLntbEN9MxA9xcYjsxS1jWR4AIa2Ibzx0tc44fYX/16lV6NDFLXH+YL32jwiACRBiEbf5KcXoTIsQSpzXx4N28Ja4BQoK7rgXiydbHjx/P25TaQAJEGAguWy0+2Q8PD6/Ki4R8EVl+bzBOnZY95fq9rj9zAkTI2SxdidBHqG9+skdw43borCXO/ZcJdraPWdv22uIEiLA4q7nvvCug8WTqzQveOH26fodo7g6uFe/a17W3+nFBAkRYENRdb1vkkz1CH9cPsVy/jrhr27PqMYvENYNlHAIesRiBYwRy0V+8iXP8+/fvX11Mr7L7ECueb/r48eMqm7FuI2BGWDEG8cm+7G3NEOfmdcTQw4h9/55lhm7DekRYKQPZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==", title: "暂无数据" } - ), /* @__PURE__ */ import_react.default.createElement("span", { className: (0, import_classnames.default)(`${componentName}__empty--text`) }, "暂无匹配数据")), !!url && openRoll && /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__scoll-module`) }, /* @__PURE__ */ import_react.default.createElement( + ), /* @__PURE__ */ import_react.default.createElement("span", { className: (0, import_classnames.default)(`${componentName}__empty--text`) }, "暂无匹配数据")), !!dataSource.length && openRoll && /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__scoll-module`) }, /* @__PURE__ */ import_react.default.createElement( import_antd.Button, { type: "default", className: (0, import_classnames.default)(`${componentName}__scoll-module__btn`), - disabled: !urls[urls.findIndex((v) => v === showUrl) - 1], + disabled: currentIndex <= 0, onClick: () => { - handlePre(); + handleIndexChange(-1); } }, /* @__PURE__ */ import_react.default.createElement(import_iconfont.default, { icon: "icon-qiehuanzuo", size: 40 }) @@ -120,13 +113,13 @@ var CompaterImage = (props) => { { type: "default", className: (0, import_classnames.default)(`${componentName}__scoll-module__btn`), - disabled: !urls[urls.findIndex((v) => v === showUrl) + 1], + disabled: currentIndex >= dataSource.length - 1, onClick: () => { - handleNext(); + handleIndexChange(1); } }, /* @__PURE__ */ import_react.default.createElement(import_iconfont.default, { icon: "icon-qiehuanyou", size: 40 }) - )), !!score && /* @__PURE__ */ import_react.default.createElement(import_CornerScore.default, { scoreTxt: score }), /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__tool`) }, /* @__PURE__ */ import_react.default.createElement( + )), showScore && /* @__PURE__ */ import_react.default.createElement(import_CornerScore.default, { scoreTxt: dataSource[currentIndex].score }), /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__tool`) }, /* @__PURE__ */ import_react.default.createElement( import_antd.Button, { type: "text", @@ -160,5 +153,5 @@ var CompaterImage = (props) => { /* @__PURE__ */ import_react.default.createElement(import_iconfont.default, { size: 16, icon: "icon-zhongzhi3" }), /* @__PURE__ */ import_react.default.createElement("span", null, "重置") ))); -}; -var ImagePreview_default = CompaterImage; +}); +var CompareImage_default = CompareImage; diff --git a/packages/meta/lib/ImagePreview/components/CornerScore/index.d.ts b/packages/meta/lib/CompareImage/components/CornerScore/index.d.ts similarity index 100% rename from packages/meta/lib/ImagePreview/components/CornerScore/index.d.ts rename to packages/meta/lib/CompareImage/components/CornerScore/index.d.ts diff --git a/packages/meta/lib/ImagePreview/components/CornerScore/index.js b/packages/meta/lib/CompareImage/components/CornerScore/index.js similarity index 97% rename from packages/meta/lib/ImagePreview/components/CornerScore/index.js rename to packages/meta/lib/CompareImage/components/CornerScore/index.js index f4800a2..916d94f 100644 --- a/packages/meta/lib/ImagePreview/components/CornerScore/index.js +++ b/packages/meta/lib/CompareImage/components/CornerScore/index.js @@ -26,7 +26,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/ImagePreview/components/CornerScore/index.tsx +// src/CompareImage/components/CornerScore/index.tsx var CornerScore_exports = {}; __export(CornerScore_exports, { CornerScore: () => CornerScore, diff --git a/packages/meta/lib/CompareImage/components/CornerScore/index.less b/packages/meta/lib/CompareImage/components/CornerScore/index.less new file mode 100644 index 0000000..cb8bf35 --- /dev/null +++ b/packages/meta/lib/CompareImage/components/CornerScore/index.less @@ -0,0 +1,21 @@ +.zhst-image__CornerScore { + position: absolute; + right: 0; + bottom: 0; + width: 56px; + height: 22px; + line-height: 22px; + text-align: right; + padding-right: 1px; + background-size: 100%; + background-image: url('data: image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAAAsCAYAAAC9rDzHAAAByUlEQVR4Xu2cO08DMRCEJy0tlNBCSwmU0EIJLbS0UEILLTX/Fo3kk1AUHrrsjB3dWIoUnZTdvfnOZ6+1mxXGGHsADgEcA9hvnyMAvJ7xiwKrjuoQ0HmDxu8ZMxToAZDQrgAE2gxg6z9xAjwFcAvgoCDumGgKuADeA7iI6vUKqAFyE/KU12U9uMmiGuBr4Ong0bIS4A2Aa234sa4CyFzuPfLqFVABfGg5nv4OFu5BAZAbl4+F62q7fQVAJul3tjtYuCMFwEcATNozDAooAL7ltMVATngS8+kLP54UMzAAjc9VABrFVrgKQIWqRpsBaBRb4SoAFaoabQagUWyFqwBUqGq0GYBGsRWuAlChqtFmABrFVrgKQIWqRpsBaBRb4SoAFaoabVYDZLU1K9EyTApUA2RzyrMp9rgRlBWylIIlFRkmBapnIIuZ0hJmgkc3lQBTzGQEN7mqApjNSwd4VTOQr8yXFDL1IbjtDOTMY/dR1r0+/LZaA1n7yb6/wOsEb+4rlMDYdZR0oSO4uZuYtEkPAO17CP9dA3nCwll3Mlj8iw/nL4ABN/gj8hPAgBsc3KY1kJuTs7Y5yV+B7BBA5nKXrSUsKcGOgJvC/ALSJBp5mBHCFAAAAABJRU5ErkJggg=='); + z-index: 99; + + &>span { + padding-right: 6px; + line-height: 22px; + font-size: 12px; + vertical-align: middle; + color: rgba(255, 255, 255, 100%); + } +} diff --git a/packages/meta/src/ImagePreview/images/emptyImage.png b/packages/meta/lib/CompareImage/images/emptyImage.png similarity index 100% rename from packages/meta/src/ImagePreview/images/emptyImage.png rename to packages/meta/lib/CompareImage/images/emptyImage.png diff --git a/packages/meta/src/ImagePreview/images/percent_background.png b/packages/meta/lib/CompareImage/images/percent_background.png similarity index 100% rename from packages/meta/src/ImagePreview/images/percent_background.png rename to packages/meta/lib/CompareImage/images/percent_background.png diff --git a/packages/meta/lib/CompareImage/index.d.ts b/packages/meta/lib/CompareImage/index.d.ts new file mode 100644 index 0000000..a72b6a9 --- /dev/null +++ b/packages/meta/lib/CompareImage/index.d.ts @@ -0,0 +1,3 @@ +import CompareImage from "./CompareImage"; +export type { CompareImageProps } from './CompareImage'; +export default CompareImage; diff --git a/packages/meta/lib/CompareImage/index.js b/packages/meta/lib/CompareImage/index.js new file mode 100644 index 0000000..2db3382 --- /dev/null +++ b/packages/meta/lib/CompareImage/index.js @@ -0,0 +1,36 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/CompareImage/index.tsx +var CompareImage_exports = {}; +__export(CompareImage_exports, { + default: () => CompareImage_default +}); +module.exports = __toCommonJS(CompareImage_exports); +var import_CompareImage = __toESM(require("./CompareImage")); +var CompareImage_default = import_CompareImage.default; diff --git a/packages/meta/lib/CompareImage/index.less b/packages/meta/lib/CompareImage/index.less new file mode 100644 index 0000000..378f365 --- /dev/null +++ b/packages/meta/lib/CompareImage/index.less @@ -0,0 +1,147 @@ +.zhst-image__compater-view { + display: flex; + width: 100%; + align-items: center; + justify-content: center; + + &>div:first-child { + margin-right: 25px; + } + + &>div:last-child { + margin-left: 25px; + } + + &__container { + position: relative; + width: 345px; + height: 460px; + box-sizing: content-box; + border: 1px solid #f0f0f0; + } + + &__view { + width: 345px; + height: 460px; + } + + &__label { + position: absolute; + z-index: 99; + top: 0; + left: 0; + display: flex; + height: 34px; + align-items: center; + justify-content: center; + + // width: 48px; + padding: 0 6px; + background: #09f; + color: #fff; + } + + &__tool { + display: flex; + width: 345px; + height: 40px; + align-items: center; + justify-content: center; + background: #f9f9f9; + + i, + span { + color: #333 !important; + } + + i { + margin-right: 4px; + } + + &>*:not(:last-child) { + margin-right: 20px; + } + + &__scale { + display: inline-block; + width: 38px; + height: 16px; + + // margin-left: 15px; + box-sizing: content-box; + border: 1px solid rgb(77 77 77 / 100%); + background: rgb(255 255 255 / 100%); + border-radius: 2px; + color: #4d4d4d; + cursor: default; + font-size: 12px; + line-height: 16px; + text-align: center; + } + + &__line { + width: 1px; + height: 14px; + background: #e6e6e6; + } + } + + &__empty { + position: absolute; + z-index: 9; + display: flex; + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background: #f9f9f9; + transform: translateY(-100%); + + &>img { + width: 140px; + height: 80px; + } + + &--text { + color: #999; + font-size: 14px; + line-height: 22px; + } + } + + &__scoll-module { + position: absolute; + top: 0%; + left: 0%; + display: flex; + width: 100%; + height: 100%; + align-items: flex-end; + justify-content: space-between; + pointer-events: none; + + &__btn { + display: flex; + width: 50px; + height: 50px; + align-items: center; + justify-content: center; + margin: 6px; + border-radius: 50%; + opacity: 0.5; + pointer-events: all; + + &>span { + display: flex; + align-items: center; + justify-content: center; + } + } + + &__btn:hover { + background-color: #09f !important; + color: #fff !important; + } + } +} diff --git a/packages/meta/lib/ImageEditor/cropper/event.js b/packages/meta/lib/ImageEditor/cropper/event.js index 22b83e9..d47e644 100644 --- a/packages/meta/lib/ImageEditor/cropper/event.js +++ b/packages/meta/lib/ImageEditor/cropper/event.js @@ -40,20 +40,20 @@ var import_constants = require("./constants"); var event_default = { bind() { const { container, element, eventHandleList = [], option } = this; - const handleCropStart = (0, import_func.addEventlistener)( + const handleCropStart = (0, import_func.addEventListenerWrapper)( container, import_constants.EVENT_POINTER_DOWN, this.onCropStart.bind(this) ); eventHandleList.push(handleCropStart); - const handleCropMove = (0, import_func.addEventlistener)( + const handleCropMove = (0, import_func.addEventListenerWrapper)( element.ownerDocument, import_constants.EVENT_POINTER_MOVE, this.onCropMove.bind(this) ); eventHandleList.push(handleCropMove); import_constants.EVENT_POINTER_UP.trim().split(import_constants.REGEXP_SPACES).forEach((eventName) => { - const handleCropEnd = (0, import_func.addEventlistener)( + const handleCropEnd = (0, import_func.addEventListenerWrapper)( element.ownerDocument, eventName, this.onCropEnd.bind(this) diff --git a/packages/meta/lib/ImageEditor/cropper/viewerBridge.js b/packages/meta/lib/ImageEditor/cropper/viewerBridge.js index aebd446..f0ac94d 100644 --- a/packages/meta/lib/ImageEditor/cropper/viewerBridge.js +++ b/packages/meta/lib/ImageEditor/cropper/viewerBridge.js @@ -30,11 +30,11 @@ var viewerBridge_default = { const { container, element, eventHandleList = [], option } = this; if (this.options.viewer) { const viewer = this.options.viewer; - const handleWhele = (0, import_func.addEventlistener)(container, import_constants.EVENT_WHEEL, this.onWheel.bind(this)); + const handleWhele = (0, import_func.addEventListenerWrapper)(container, import_constants.EVENT_WHEEL, this.onWheel.bind(this)); eventHandleList.push(handleWhele); this.onTransformChange(viewer); this.limited = true; - const handleTransformChange = (0, import_func.addEventlistener)( + const handleTransformChange = (0, import_func.addEventListenerWrapper)( viewer.element, import_constants2.EVENT_VIEWER_TRANSFORM_CHANGE, (event) => { diff --git a/packages/meta/lib/ImageEditor/viewer/event.js b/packages/meta/lib/ImageEditor/viewer/event.js index 40d67c0..d830963 100644 --- a/packages/meta/lib/ImageEditor/viewer/event.js +++ b/packages/meta/lib/ImageEditor/viewer/event.js @@ -50,25 +50,25 @@ var event_default = { const { canvas, element, eventHandleList = [], options } = this; const scaleAble = (0, import_func.get)(options, "scaleAble", true); if (scaleAble) { - const handleWhele = (0, import_func.addEventListener)(canvas, import_constants.EVENT_WHEEL, this.onWheel.bind(this)); + const handleWhele = (0, import_func.addEventListenerWrapper)(canvas, import_constants.EVENT_WHEEL, this.onWheel.bind(this)); eventHandleList.push(handleWhele); } const dragAble = (0, import_func.get)(options, "dragAble", true); if (dragAble) { - const handleDragStart = (0, import_func.addEventListener)( + const handleDragStart = (0, import_func.addEventListenerWrapper)( canvas, import_constants.EVENT_POINTER_DOWN, this.onDragStart.bind(this) ); - eventHandleList.push(import_func.addEventListener); - const handleDragMove = (0, import_func.addEventListener)( + eventHandleList.push(import_func.addEventListenerWrapper); + const handleDragMove = (0, import_func.addEventListenerWrapper)( element.ownerDocument, import_constants.EVENT_POINTER_MOVE, this.onDragMove.bind(this) ); eventHandleList.push(handleDragMove); import_constants.EVENT_POINTER_UP.trim().split(import_constants.REGEXP_SPACES).forEach((eventName) => { - const handleDragEnd = (0, import_func.addEventListener)( + const handleDragEnd = (0, import_func.addEventListenerWrapper)( element.ownerDocument, eventName, this.onDragEnd.bind(this) @@ -76,7 +76,7 @@ var event_default = { eventHandleList.push(handleDragEnd); }); } - const handleClick = (0, import_func.addEventListener)(canvas, import_constants.EVENT_CLICK, this.onClick.bind(this)); + const handleClick = (0, import_func.addEventListenerWrapper)(canvas, import_constants.EVENT_CLICK, this.onClick.bind(this)); eventHandleList.push(handleClick); }, unbind() { diff --git a/packages/meta/lib/ImagePreview/index.d.ts b/packages/meta/lib/ImagePreview/index.d.ts deleted file mode 100644 index 31fba43..0000000 --- a/packages/meta/lib/ImagePreview/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { FC } from 'react'; -export interface CompaterImageProps { - url: string; - label: string; - openRoll?: boolean; - urls?: Array; - specialTitle: String; - noTargetImageTip?: string; - score?: number; -} -declare const CompaterImage: FC; -export default CompaterImage; diff --git a/packages/meta/lib/VideoPlayer/VideoPlayer.d.ts b/packages/meta/lib/VideoPlayer/VideoPlayer.d.ts new file mode 100644 index 0000000..cf56091 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/VideoPlayer.d.ts @@ -0,0 +1,18 @@ +import React, { Dispatch, ReactElement, SetStateAction } from 'react'; +import { Rect, IScreenshotButtonProp, AlignType } from '@zhst/types'; +import './index.less'; +export interface VideoViewProps { + url: string; + maxDuration?: number; + screenshotButtonAlign?: AlignType; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; + defautlNormalizationRect?: Rect; + onCropChange?: (showCrop: boolean, normalizationRect: null | Rect) => void; +} +export interface VideoViewRef { + cropAble: boolean; + setShowCrop: Dispatch>; + downloadVideoframe: () => void; +} +declare const VideoPlayer: React.ForwardRefExoticComponent>; +export default VideoPlayer; diff --git a/packages/meta/lib/VideoPlayer/VideoPlayer.js b/packages/meta/lib/VideoPlayer/VideoPlayer.js new file mode 100644 index 0000000..00c8880 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/VideoPlayer.js @@ -0,0 +1,611 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/VideoPlayer/VideoPlayer.tsx +var VideoPlayer_exports = {}; +__export(VideoPlayer_exports, { + default: () => VideoPlayer_default +}); +module.exports = __toCommonJS(VideoPlayer_exports); +var import_react = __toESM(require("react")); +var import_func = require("@zhst/func"); +var import_rc_align = __toESM(require("rc-align")); +var import_hooks = require("@zhst/hooks"); +var import_classnames = __toESM(require("classnames")); +var import_downloadjs = __toESM(require("downloadjs")); +var import_antd = require("antd"); +var import_iconfont = __toESM(require("../iconfont")); +var import_ImageEditor = require("../ImageEditor"); +var import_FlvPlayer = __toESM(require("./components/FlvPlayer")); +var import_Progress = __toESM(require("./components/Progress")); +var import_Loading = __toESM(require("./components/Loading")); +var import_ScreenhotButtons = __toESM(require("../BigImagePreview/components/ScreenhotButtons")); +var import_constants = require("../utils/constants"); +var import_videoPlayerHelper = require("./videoPlayerHelper"); +var import_index = require("./index.less"); +var componentName = `zhst-image__video-view`; +var VideoPlayer = (0, import_react.forwardRef)((props, ref) => { + const { + url, + maxDuration, + screenshotButtonAlign = { + points: ["bl", "br"], + offset: [6, 0], + overflow: { + adjustX: true, + adjustY: true + } + }, + screenshotButtonRender = (0, import_ScreenhotButtons.default)({ + onBigImageActionClick: () => { + }, + disableBtn: [] + }), + onCropChange, + defautlNormalizationRect: defaultNormalizationRect + } = props; + const videoType = (0, import_react.useMemo)(() => url && url.startsWith("http") ? "mp4" : "flv", [url]); + const containerRef = (0, import_react.useRef)(null); + const videoRef = (0, import_react.useRef)(null); + const videoInsRef = (0, import_react.useRef)(null); + const [playSeq, setPlaySeq] = (0, import_react.useState)(0); + const videoRemoveListener = (0, import_react.useRef)(import_func.noop); + const loadingTimeRef = (0, import_react.useRef)(0); + const delayLoadingTimer = (0, import_react.useRef)(null); + const [isReady, setIsReady] = (0, import_react.useState)(false); + const [isPlay, setIsPlay] = (0, import_react.useState)(false); + const [isEnd, setIsEnd] = (0, import_react.useState)(false); + const [isError, setIsError] = (0, import_react.useState)(false); + const [isVideoLoadFinished, setIsVideoLoadFinish] = (0, import_react.useState)(false); + const [playTime, setPlayTime] = (0, import_react.useState)(0); + const [isLoadingVideo, setIsLoadingVideo] = (0, import_react.useState)(true); + const [isDelayLoading, setIsDelayLoading] = (0, import_react.useState)(false); + const latestIsLoadingVideo = (0, import_hooks.useLatest)(isLoadingVideo); + const setIsLoadingVideoWrapper = (isLoading) => { + setIsLoadingVideo((preLoading) => { + if (!preLoading && isLoading) { + loadingTimeRef.current = (/* @__PURE__ */ new Date()).getTime(); + } + if (!isLoading) { + loadingTimeRef.current = null; + } + if (!isLoading) { + setIsDelayLoading(false); + } + if (!delayLoadingTimer.current && preLoading) { + delayLoadingTimer.current = setTimeout(() => { + if (latestIsLoadingVideo.current) { + setIsDelayLoading(true); + } + delayLoadingTimer.current = null; + }, 200); + } + return isLoading; + }); + }; + (0, import_react.useEffect)(() => { + let timer = setInterval(() => { + if (loadingTimeRef.current) { + if ((/* @__PURE__ */ new Date()).getTime() - loadingTimeRef.current > 1e3 * 30) { + checkIsErr(); + } + } + }, 1e3); + return () => { + clearInterval(timer); + }; + }, []); + (0, import_hooks.useUpdateEffect)(() => { + var _a, _b; + if (isEnd) { + (_b = (_a = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _a.pause) == null ? void 0 : _b.call(_a); + } + }, [isEnd]); + const checkIsErr = () => { + var _a, _b; + setIsError(true); + try { + (_b = (_a = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _a.destroy) == null ? void 0 : _b.call(_a); + } catch (error) { + console.error(error); + } + }; + const latestMaxDuration = (0, import_hooks.useLatest)(maxDuration); + const initPlayer = (0, import_react.useCallback)((ins, dom) => { + videoRef.current = dom; + videoInsRef.current = ins; + const maxDuration2 = latestMaxDuration.current || 0; + let video = dom; + let errorLister = (e) => { + checkIsErr(); + console.error("视频出错了", e, video.currentTime); + }; + let waitingListener = (e) => { + setIsLoadingVideoWrapper(true); + console.debug("视频加载等待", e, video.currentTime); + }; + let playingListener = (e) => { + setIsLoadingVideoWrapper(false); + setIsError(false); + console.debug("视频从等待中播放", e, video.currentTime); + }; + let playLister = (e) => { + setIsPlay(true); + setIsError(false); + console.debug("提示该视频正在播放中", e, video.currentTime); + }; + let pauseListener = (e) => { + setIsPlay(false); + console.debug("暂停播放", e, video.currentTime); + }; + let endedListner = (e) => { + setIsEnd(true); + setIsVideoLoadFinish(true); + console.debug("视频播放完了", e, video.currentTime); + }; + let timeupdateListner = (e) => { + var _a; + console.debug( + "视频播放时间更新", + e, + video.currentTime, + (_a = videoRef.current) == null ? void 0 : _a.duration, + maxDuration2 + ); + let nowTime = video.currentTime; + if (nowTime >= maxDuration2) { + setIsEnd(true); + setIsVideoLoadFinish(true); + } + setPlayTime(nowTime); + }; + let windowErrorHandle = (errorEvent) => { + try { + if (errorEvent["message"] == "Uncaught TypeError: Cannot read property 'flushStashedSamples' of null") { + checkIsErr(); + console.error("视频出错了 window监听", errorEvent); + } + } catch (error) { + console.error(error); + } + }; + video.addEventListener("error", errorLister); + video.addEventListener("waiting", waitingListener); + video.addEventListener("playing", playingListener); + video.addEventListener("play", playLister); + video.addEventListener("pause", pauseListener); + video.addEventListener("ended", endedListner); + video.addEventListener("timeupdate", timeupdateListner); + window.addEventListener("error", windowErrorHandle); + videoRemoveListener.current = () => { + video.removeEventListener("error", errorLister); + video.removeEventListener("waiting", waitingListener); + video.removeEventListener("playing", playingListener); + video.removeEventListener("play", playLister); + video.removeEventListener("pause", pauseListener); + video.removeEventListener("ended", endedListner); + video.removeEventListener("timeupdate", timeupdateListner); + window.removeEventListener("error", windowErrorHandle); + }; + videoInsRef == null ? void 0 : videoInsRef.current.on(import_FlvPlayer.FLV_EVENT.ERROR, (type, errDetail, info) => { + checkIsErr(); + console.error("videoInsRef 错误", type, errDetail, info, video.currentTime); + }); + let playPromise = videoInsRef == null ? void 0 : videoInsRef.current.play(); + setIsReady(true); + playPromise.then(() => { + setIsReady(true); + }).catch((...arg) => { + try { + } catch (error) { + } + console.error("playPromise视频出错了", arg); + }); + }, []); + (0, import_hooks.useUnmount)(() => { + try { + videoRemoveListener.current(); + } catch (e) { + console.error(e); + } + }); + const reload = async () => { + if (videoInsRef.current) { + let oldTime = videoInsRef.current.currentTime; + videoInsRef.current.currentTime = 0; + if (oldTime === videoInsRef.current.currentTime) { + setIsReady(false); + setIsPlay(false); + setIsLoadingVideoWrapper(false); + setIsReady(false); + setIsEnd(false); + setIsVideoLoadFinish(false); + setPlayTime(0); + try { + videoRemoveListener.current(); + } catch (error) { + console.error(error); + } + setPlaySeq((pre) => pre + 1); + return; + } + videoInsRef.current.play(); + } + setPlayTime(0); + setIsEnd(false); + }; + const seek = (v) => { + if (videoInsRef.current && isVideoLoadFinished) { + setPlayTime(parseFloat(v)); + videoInsRef.current.currentTime = parseFloat(v); + } else { + import_antd.message.warning("待视频加载完,才可操作进度条"); + } + }; + const [isFullscreen, { toggleFullscreen }] = (0, import_hooks.useFullscreen)(containerRef, { + pageFullscreen: true + }); + const showMaxDuration = !!maxDuration ? maxDuration : (0, import_func.toRealNumber)((0, import_func.get)(videoRef, "current.duration", 0)); + const showSlider = videoInsRef.current && isVideoLoadFinished; + const showStatus = (0, import_videoPlayerHelper.getShowStatus)(isDelayLoading, isEnd, isError); + const corpContainerRef = (0, import_react.useRef)(); + const cropInsRef = (0, import_react.useRef)(null); + const [showCrop, setShowCrop] = (0, import_react.useState)(false); + const isFirstFlagRef = (0, import_react.useRef)(true); + (0, import_react.useEffect)(() => { + const isFirst = isFirstFlagRef.current; + if (!isLoadingVideo && isReady && isFirst && defaultNormalizationRect && !showStatus) { + (0, import_func.nextTick)(() => { + setShowCrop(true); + }); + } + }, [isLoadingVideo, showStatus]); + const alginContainerRef = (0, import_react.useRef)(null); + const alignRef = (0, import_react.useRef)(null); + const [cropRect, setCropRect] = (0, import_react.useState)(null); + (0, import_react.useEffect)(() => { + var _a, _b; + showCrop ? (_a = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _a.pause() : (_b = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _b.play(); + }, [showCrop]); + (0, import_react.useEffect)(() => { + var _a; + let handlerCropStart; + let handlerCropEnd; + setCropRect(null); + if (!isReady) + return; + if (showCrop) { + handlerCropStart = (0, import_func.addEventListenerWrapper)(corpContainerRef.current, import_ImageEditor.EVENT_CROP_START, () => { + setCropRect(null); + }); + handlerCropEnd = (0, import_func.addEventListenerWrapper)(corpContainerRef.current, import_ImageEditor.EVENT_CROP_END, (event) => { + var _a2, _b; + const data = event.detail; + setCropRect({ + x: data.left, + y: data.top, + w: data.width, + h: data.height + }); + (_b = (_a2 = alignRef == null ? void 0 : alignRef.current) == null ? void 0 : _a2.forceAlign) == null ? void 0 : _b.call(_a2); + }); + let video = videoRef.current; + let scale = Math.min( + video.offsetWidth / video.videoWidth, + video.offsetHeight / video.videoHeight + ); + let finalVideoWidth = video.videoWidth * scale; + let finalVideoHeight = video.videoHeight * scale; + let cropBoxLimited = { + width: finalVideoWidth, + height: finalVideoHeight, + top: (video.offsetHeight - finalVideoHeight) / 2, + left: (video.offsetWidth - finalVideoWidth) / 2 + }; + let canvas = document.createElement("canvas"); + canvas.width = video.offsetWidth; + canvas.height = video.offsetHeight; + canvas.style.display = "none"; + document.body.appendChild(canvas); + let ctx = canvas.getContext("2d"); + ctx == null ? void 0 : ctx.drawImage( + video, + (video.offsetWidth - finalVideoWidth) / 2, + (video.offsetHeight - finalVideoHeight) / 2, + finalVideoWidth, + finalVideoHeight + ); + let imageData = canvas.toDataURL("image/png"); + (_a = canvas.parentNode) == null ? void 0 : _a.removeChild(canvas); + const isFirst = isFirstFlagRef.current; + let initialCropBoxData = null; + if (isFirst && defaultNormalizationRect) { + initialCropBoxData = { + left: defaultNormalizationRect.x * finalVideoWidth + cropBoxLimited.left, + top: defaultNormalizationRect.y * finalVideoHeight + cropBoxLimited.top, + width: defaultNormalizationRect.w * finalVideoWidth, + height: defaultNormalizationRect.h * finalVideoHeight + }; + } + isFirstFlagRef.current = false; + cropInsRef.current = new import_ImageEditor.Cropper(corpContainerRef.current, { + showMask: true, + cropBoxLimited, + img: imageData, + initialCropBoxData + }); + } + return () => { + var _a2, _b; + handlerCropStart == null ? void 0 : handlerCropStart.remove(); + handlerCropEnd == null ? void 0 : handlerCropEnd.remove(); + (_b = (_a2 = cropInsRef == null ? void 0 : cropInsRef.current) == null ? void 0 : _a2.destroy) == null ? void 0 : _b.call(_a2); + cropInsRef.current = null; + }; + }, [showCrop, isReady]); + const latestCropRect = (0, import_hooks.useLatest)(cropRect); + const getCropInfo = async () => { + var _a; + const cropRect2 = latestCropRect.current; + let video = videoRef.current; + if (!video) + return; + let rectList = []; + let extendRectList = []; + let selectIndex = 0; + let scale = Math.min( + video.offsetWidth / video.videoWidth, + video.offsetHeight / video.videoHeight + ); + let finalVideoWidth = video.videoWidth * scale; + let finalVideoHeight = video.videoHeight * scale; + let canvas = document.createElement("canvas"); + canvas.width = finalVideoWidth; + canvas.height = finalVideoHeight; + canvas.style.display = "none"; + document.body.appendChild(canvas); + let ctx = canvas.getContext("2d"); + ctx.drawImage( + video, + 0, + 0, + finalVideoWidth, + finalVideoHeight + ); + let base64 = canvas.toDataURL("image/jpeg"); + const blobData = (0, import_func.dataURLToBlob)(base64); + (_a = canvas.parentNode) == null ? void 0 : _a.removeChild(canvas); + const file = new window.File([blobData], `${(/* @__PURE__ */ new Date()).getTime()}`); + let newRect = { + w: cropRect2.w / finalVideoWidth, + h: cropRect2.h / finalVideoHeight, + x: (cropRect2.x - (video.offsetWidth - finalVideoWidth) / 2) / finalVideoWidth, + y: (cropRect2.y - (video.offsetHeight - finalVideoHeight) / 2) / finalVideoHeight + }; + rectList.push(newRect); + extendRectList.push(newRect); + extendRectList.forEach(async (rect, index) => { + extendRectList[index] = { + ...rect + }; + }); + return { + rectList, + extendRectList, + selectIndex, + file + }; + }; + (0, import_react.useEffect)(() => { + let normalizationRect = null; + if (showCrop && cropRect) { + let video = videoRef.current; + let scale = Math.min( + video.offsetWidth / video.videoWidth, + video.offsetHeight / video.videoHeight + ); + let finalVideoWidth = video.videoWidth * scale; + let finalVideoHeight = video.videoHeight * scale; + let cropBoxLimited = { + width: finalVideoWidth, + height: finalVideoHeight, + top: (video.offsetHeight - finalVideoHeight) / 2, + left: (video.offsetWidth - finalVideoWidth) / 2 + }; + normalizationRect = { + x: (cropRect.x - cropBoxLimited.left) / cropBoxLimited.width, + y: (cropRect.y - cropBoxLimited.top) / cropBoxLimited.height, + w: cropRect.w / cropBoxLimited.width, + h: cropRect.h / cropBoxLimited.height + }; + } + onCropChange == null ? void 0 : onCropChange(showCrop, normalizationRect); + }, [showCrop, cropRect]); + const downloadVideoframe = (0, import_react.useCallback)(async () => { + var _a, _b; + try { + (_b = (_a = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _a.pause) == null ? void 0 : _b.call(_a); + let video = videoRef.current; + var canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + let base64; + if (video.readyState === 0) { + ctx == null ? void 0 : ctx.clearRect(0, 0, canvas.width, canvas.height); + canvas.width = video.offsetWidth; + canvas.height = video.offsetHeight; + ctx.fillStyle = "black"; + ctx == null ? void 0 : ctx.fillRect(0, 0, canvas.width, canvas.height); + base64 = canvas.toDataURL(); + } else { + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + ctx == null ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height); + base64 = canvas.toDataURL("image/png"); + } + (0, import_downloadjs.default)(base64); + } catch (error) { + console.error(error); + } + }, []); + const latestIsReady = (0, import_hooks.useLatest)(isReady); + const cropAble = !showStatus && isReady; + (0, import_react.useImperativeHandle)(ref, () => ({ + cropAble, + setShowCrop: (dispatch) => { + const isReady2 = latestIsReady.current; + if (!isReady2) + return; + setShowCrop(dispatch); + }, + downloadVideoframe + })); + return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}`), ref: containerRef }, url && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( + import_FlvPlayer.default, + { + playId: playSeq, + autoPlay: true, + className: (0, import_classnames.default)(`${componentName}-flv`), + type: videoType, + url, + config: { + enableStashBuffer: true, + stashInitialSize: 1024 * 700, + isLive: true, + hasAudio: false, + hasVideo: true + }, + onCreat: initPlayer + } + ), /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)(`${componentName}-crop-container`), + ref: corpContainerRef, + style: { + display: isFullscreen ? "none" : "block" + } + } + ), showCrop && cropRect && screenshotButtonRender && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( + "div", + { + ref: alginContainerRef, + className: (0, import_classnames.default)(`${componentName}-align`), + style: Object.assign( + { + width: cropRect.w, + height: cropRect.h + }, + (0, import_func.getTransforms)({ + translateX: cropRect.x, + translateY: cropRect.y + }) + ) + } + ), /* @__PURE__ */ import_react.default.createElement( + import_rc_align.default, + { + ref: alignRef, + monitorWindowResize: true, + align: screenshotButtonAlign, + target: function() { + return alginContainerRef.current; + } + }, + screenshotButtonRender({ + model: "IMAGE", + getCropInfo, + setShowCrop, + cropType: import_constants.CROP_TYPE["CUSTOM"] + }) + )), !showCrop && /* @__PURE__ */ import_react.default.createElement("div", { className: `${componentName}-opt` }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: (e) => { + var _a, _b; + if (!isPlay) { + (_a = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _a.play(); + setShowCrop(false); + } else { + (_b = videoInsRef == null ? void 0 : videoInsRef.current) == null ? void 0 : _b.pause(); + } + } + }, + /* @__PURE__ */ import_react.default.createElement( + import_iconfont.default, + { + styles: { + color: "#fff", + display: "flex" + }, + color: "#1890ff", + icon: !isPlay ? "icon-shipinbofang" : "icon-shipinzanting" + } + ) + )), /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: `${componentName}-opt-range`, + onClick: (e) => { + e.stopPropagation(); + } + }, + /* @__PURE__ */ import_react.default.createElement( + import_Progress.default, + { + value: playTime, + min: 0, + max: showMaxDuration, + showSlider, + onChange: seek + } + ), + /* @__PURE__ */ import_react.default.createElement("div", null, (0, import_func.formatDurationTime)(playTime), "/", (0, import_func.formatDurationTime)(showMaxDuration)) + ), /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement( + import_antd.Button, + { + type: "text", + onClick: (e) => { + e.stopPropagation(); + toggleFullscreen(); + } + }, + /* @__PURE__ */ import_react.default.createElement( + import_iconfont.default, + { + styles: { + color: "#fff", + display: "flex" + }, + size: 18, + icon: isFullscreen ? "icon-cancle_fullscreen" : "icon-fullscreen" + } + ) + ))), !!showStatus && /* @__PURE__ */ import_react.default.createElement(import_Loading.default, { status: showStatus, reload: () => reload() }))); +}); +var VideoPlayer_default = VideoPlayer; diff --git a/packages/meta/lib/VideoPlayer/components/FlvPlayer/index.d.ts b/packages/meta/lib/VideoPlayer/components/FlvPlayer/index.d.ts new file mode 100644 index 0000000..646b267 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/FlvPlayer/index.d.ts @@ -0,0 +1,46 @@ +import React, { Component, CSSProperties } from 'react'; +import flvjs from 'flv.js'; +export declare const FLV_EVENT: Readonly; +export interface VideoPlayerProps { + className: string; + style?: CSSProperties; + type: string; + isLive?: boolean; + cors?: boolean; + withCredentials?: boolean; + playId?: number; + hasAudio?: boolean; + hasVideo?: boolean; + duration?: number; + filesize?: number; + url?: string; + autoPlay?: boolean; + onCreat?: any; + /** + * @see https://github.com/Bilibili/flv.js/blob/master/docs/api.md#config + */ + config: object; +} +export default class VideoPlayer extends Component { + state: { + curPlayUrl: string; + shouldReinit: boolean; + }; + flvPlayer: any; + videoElement: null; + static getDerivedStateFromProps: (nextProps: { + url?: any; + playId?: any; + }, prevState: { + curPlayUrl?: any; + playId?: any; + }) => { + playId: any; + curPlayUrl: any; + shouldReinit: boolean; + } | null; + initFlv: ($video: null) => void; + componentWillUnmount(): void; + componentDidUpdate(): void; + render(): React.JSX.Element; +} diff --git a/packages/meta/lib/VideoPlayer/components/FlvPlayer/index.js b/packages/meta/lib/VideoPlayer/components/FlvPlayer/index.js new file mode 100644 index 0000000..38230d2 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/FlvPlayer/index.js @@ -0,0 +1,144 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/VideoPlayer/components/FlvPlayer/index.tsx +var FlvPlayer_exports = {}; +__export(FlvPlayer_exports, { + FLV_EVENT: () => FLV_EVENT, + default: () => VideoPlayer +}); +module.exports = __toCommonJS(FlvPlayer_exports); +var import_react = __toESM(require("react")); +var import_flv = __toESM(require("flv.js")); +var import_func = require("@zhst/func"); +var FLV_EVENT = import_flv.default.Events; +var VideoPlayer = class extends import_react.Component { + constructor() { + super(...arguments); + this.state = { + curPlayUrl: "", + shouldReinit: false + }; + this.flvPlayer = null; + this.videoElement = null; + this.initFlv = ($video) => { + this.videoElement = $video; + const { className, autoPlay = true, config = {}, onCreat, playId, ...others } = this.props; + if ($video) { + if (import_flv.default.isSupported() && this.props.url && this.props.url) { + const reload = () => { + if (this.flvPlayer && this.flvPlayer.destroy) { + try { + this.flvPlayer.destroy(); + } catch (error) { + console.error(error); + } + } + let flvPlayer = import_flv.default.createPlayer({ ...others }, { + deferLoadAfterSourceOpen: false, + ...config + }); + flvPlayer.attachMediaElement($video); + flvPlayer.load(); + this.flvPlayer = flvPlayer; + let controller = this.flvPlayer._transmuxer._controller; + let wsLoader = controller._ioctl._loader; + const oldWsOnCompleteFunc = wsLoader._onComplete; + wsLoader._onComplete = function() { + if (!controller._remuxer) { + controller._remuxer = { + destroy: () => { + console.log("组件销毁"); + }, + flushStashedSamples: () => { + console.log("flushStashedSamples"); + } + }; + } + oldWsOnCompleteFunc(); + }; + this.flvPlayer.reload = reload; + onCreat && onCreat(this.flvPlayer, $video); + }; + reload(); + onCreat && onCreat(this.flvPlayer, $video); + } + } + }; + } + componentWillUnmount() { + var _a, _b; + if (this.flvPlayer) { + (_a = this.flvPlayer) == null ? void 0 : _a.unload(); + (_b = this.flvPlayer) == null ? void 0 : _b.detachMediaElement(); + } + } + componentDidUpdate() { + if (this.state.shouldReinit) { + this.setState({ shouldReinit: false }); + this.initFlv(this.videoElement); + } + } + render() { + const { className, style } = this.props; + return /* @__PURE__ */ import_react.default.createElement( + "video", + { + muted: true, + preload: "metadata", + className, + style: Object.assign( + { + width: "100%", + height: "100%" + }, + style ? style : {} + ), + ref: this.initFlv + } + ); + } +}; +VideoPlayer.getDerivedStateFromProps = (nextProps, prevState) => { + const { playId = 0 } = nextProps; + const { playId: prePlayId = 0 } = prevState; + if (nextProps.url !== void 0) { + if (!(0, import_func.isEqual)(nextProps.url, prevState.curPlayUrl) || !(0, import_func.isEqual)(playId, prePlayId)) { + return { + playId, + curPlayUrl: nextProps.url, + shouldReinit: true + }; + } + } + return null; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + FLV_EVENT +}); diff --git a/packages/meta/lib/VideoPlayer/components/Loading/index.d.ts b/packages/meta/lib/VideoPlayer/components/Loading/index.d.ts new file mode 100644 index 0000000..1509947 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/Loading/index.d.ts @@ -0,0 +1,8 @@ +import { FC } from 'react'; +import './index.less'; +export interface ILoading { + status: 'LOADING' | 'COMPLETED' | 'END' | 'ERROR' | null; + reload: () => void; +} +declare const Loading: FC; +export default Loading; diff --git a/packages/meta/lib/VideoPlayer/components/Loading/index.js b/packages/meta/lib/VideoPlayer/components/Loading/index.js new file mode 100644 index 0000000..150c54d --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/Loading/index.js @@ -0,0 +1,84 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/VideoPlayer/components/Loading/index.tsx +var Loading_exports = {}; +__export(Loading_exports, { + default: () => Loading_default +}); +module.exports = __toCommonJS(Loading_exports); +var import_react = __toESM(require("react")); +var import_antd = require("antd"); +var import_classnames = __toESM(require("classnames")); +var import_iconfont = __toESM(require("../../../iconfont")); +var import_index = require("./index.less"); +var componentName = `zhst-image__video-view`; +var Loading = (props) => { + const { status, reload } = props; + return /* @__PURE__ */ import_react.default.createElement( + "div", + { + className: (0, import_classnames.default)(`${componentName}__player-mask`), + onClick: (e) => { + e.stopPropagation(); + } + }, + status === "LOADING" && /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { tip: "加载中...", spinning: status === "LOADING" }), + status === "END" && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( + "div", + { + onClick: () => { + reload(); + }, + className: (0, import_classnames.default)(`${componentName}__icon-wraper`) + }, + /* @__PURE__ */ import_react.default.createElement( + import_iconfont.default, + { + styles: { + fill: "#ffffff", + color: "#ffffff" + }, + size: 54, + icon: "icon-shuaxin" + } + ) + ), /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__player-mask-title`) }, "点击刷新后,将重新播放")), + status === "ERROR" && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__icon-wraper`) }, /* @__PURE__ */ import_react.default.createElement( + import_iconfont.default, + { + styles: { + color: "#ffffff" + }, + size: 54, + icon: "icon-jiazaishibai" + } + )), /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(`${componentName}__player-mask-title`) }, "视频加载失败,", /* @__PURE__ */ import_react.default.createElement("a", { onClick: reload }, " ", "刷新"))) + ); +}; +var Loading_default = Loading; diff --git a/packages/meta/lib/VideoPlayer/components/Loading/index.less b/packages/meta/lib/VideoPlayer/components/Loading/index.less new file mode 100644 index 0000000..b6c11a2 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/Loading/index.less @@ -0,0 +1,53 @@ +.zhst-image__video-view__player-mask { + position: absolute; + width: 100%; + height: 100%; + z-index: 99; + top: 0; + right: 0; + bottom: 0; + left: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: rgb(4 4 4 / 70%); + + &--bg { + z-index: 999; + background-color: rgb(4 4 4 / 100%); + } + + i { + cursor: pointer; + } + + &-title { + margin-top: 12px; + color: #fff; + text-align: center; + + & a { + color: #09f; + cursor: pointer; + text-decoration: underline; + } + } +} + +.zhst-image__video-view__icon-wraper { + display: flex; + width: 80px; + height: 80px; + align-items: center; + justify-content: center; + background-color: rgb(255 255 255 / 10%); + border-radius: 50%; + cursor: pointer; + line-height: 80px; + text-align: center; + + // &:hover { + // background: #0099ff; + // } +} diff --git a/packages/meta/lib/VideoPlayer/components/Progress/index.d.ts b/packages/meta/lib/VideoPlayer/components/Progress/index.d.ts new file mode 100644 index 0000000..7fb0a10 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/Progress/index.d.ts @@ -0,0 +1,10 @@ +import React from 'react'; +import type { SliderSingleProps } from 'antd'; +import './index.less'; +export interface RangeWrapperProps extends SliderSingleProps { + showSlider: boolean; + className?: string; + min: number; +} +export declare const Range: React.FC; +export default Range; diff --git a/packages/meta/lib/VideoPlayer/components/Progress/index.js b/packages/meta/lib/VideoPlayer/components/Progress/index.js new file mode 100644 index 0000000..92e0d85 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/Progress/index.js @@ -0,0 +1,60 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/VideoPlayer/components/Progress/index.tsx +var Progress_exports = {}; +__export(Progress_exports, { + Range: () => Range, + default: () => Progress_default +}); +module.exports = __toCommonJS(Progress_exports); +var import_react = __toESM(require("react")); +var import_classnames = __toESM(require("classnames")); +var import_antd = require("antd"); +var import_index = require("./index.less"); +var componentName = `zhst-image__range`; +var Range = (props) => { + const { className, style, showSlider = true, ...others } = props; + return /* @__PURE__ */ import_react.default.createElement( + "div", + { + style, + className: (0, import_classnames.default)( + `${componentName}`, + !showSlider && `${componentName}--no-slider`, + className + ) + }, + /* @__PURE__ */ import_react.default.createElement(import_antd.Slider, { ...others }) + ); +}; +var Progress_default = Range; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Range +}); diff --git a/packages/meta/lib/VideoPlayer/components/Progress/index.less b/packages/meta/lib/VideoPlayer/components/Progress/index.less new file mode 100644 index 0000000..e922211 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/components/Progress/index.less @@ -0,0 +1,49 @@ +.zhst-image__range { + position: relative; + + &--no-slider { + .next-range-slider { + display: none; + } + } + + & .next-range .next-range-track { + height: 8px; + margin-top: -4px; + border-radius: 8px; + } + + & .next-range .next-range-selected { + height: 8px; + margin-top: -4px; + border-radius: 8px; + } + + & .next-range .next-range-slider-inner { + width: 14px; + height: 14px; + border-color: #fff; + margin-top: -7px; + margin-left: -7px; + background-color: #0098ff; + } + + & .next-range .next-range-slider { + width: 14px; + height: 14px; + margin-top: -7px; + margin-left: -7px; + } + + & .next-range.simulation-click>.next-range-slider-inner { + border: 2px solid #fff !important; + } + + & .next-range .next-range-frag.next-range-active .next-range-slider .next-range-slider-inner { + border: 2px solid #fff !important; + } + + & .next-range .next-range-slider.next-range-slider-moving .next-range-slider-inner { + border: 2px solid #fff !important; + } +} diff --git a/packages/meta/lib/VideoPlayer/index.d.ts b/packages/meta/lib/VideoPlayer/index.d.ts new file mode 100644 index 0000000..a1993e1 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/index.d.ts @@ -0,0 +1,3 @@ +import VideoPlayer from './VideoPlayer'; +export type { VideoViewProps, VideoViewRef } from './VideoPlayer'; +export default VideoPlayer; diff --git a/packages/meta/lib/VideoPlayer/index.js b/packages/meta/lib/VideoPlayer/index.js new file mode 100644 index 0000000..7d136ea --- /dev/null +++ b/packages/meta/lib/VideoPlayer/index.js @@ -0,0 +1,36 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/VideoPlayer/index.tsx +var VideoPlayer_exports = {}; +__export(VideoPlayer_exports, { + default: () => VideoPlayer_default +}); +module.exports = __toCommonJS(VideoPlayer_exports); +var import_VideoPlayer = __toESM(require("./VideoPlayer")); +var VideoPlayer_default = import_VideoPlayer.default; diff --git a/packages/meta/lib/VideoPlayer/index.less b/packages/meta/lib/VideoPlayer/index.less new file mode 100644 index 0000000..181e65c --- /dev/null +++ b/packages/meta/lib/VideoPlayer/index.less @@ -0,0 +1,75 @@ +.zhst-image__video-view { + position: relative; + overflow: hidden; + width: 100%; + height: 532px; + background-color: #333; + + // &-flv { + // width: 85%; + // } + &-screenshot { + position: absolute; + z-index: 10; + } + + &-crop-container { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + } + + &-align { + position: absolute; + top: 0; + left: 0; + pointer-events: none; + } + + &-opt { + position: absolute; + z-index: 99; + bottom: 0; + display: flex; + width: 100%; + height: 32px; + box-sizing: border-box; + align-items: center; + padding: 0 12px; + background-color: rgb(0 0 0 / 80%); + line-height: 32px; + + &>div:first-child { + display: flex; + align-items: center; + margin-right: 12px; + } + + &>div:last-child { + display: flex; + align-items: center; + margin-left: 12px; + } + + &-range { + display: flex; + height: 32px; + flex: 1; + align-items: center; + line-height: 32px; + text-align: center; + + &>div:first-child { + flex: 1; + } + + &>div:last-child { + width: 100px; + margin-left: 8px; + color: #fff; + } + } + } +} diff --git a/packages/meta/lib/VideoPlayer/videoPlayerHelper.d.ts b/packages/meta/lib/VideoPlayer/videoPlayerHelper.d.ts new file mode 100644 index 0000000..661a7c1 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/videoPlayerHelper.d.ts @@ -0,0 +1 @@ +export declare function getShowStatus(isLoadingVideo: boolean, isEnd: boolean, isError: boolean): string | null; diff --git a/packages/meta/lib/VideoPlayer/videoPlayerHelper.js b/packages/meta/lib/VideoPlayer/videoPlayerHelper.js new file mode 100644 index 0000000..6ef0b97 --- /dev/null +++ b/packages/meta/lib/VideoPlayer/videoPlayerHelper.js @@ -0,0 +1,41 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/VideoPlayer/videoPlayerHelper.ts +var videoPlayerHelper_exports = {}; +__export(videoPlayerHelper_exports, { + getShowStatus: () => getShowStatus +}); +module.exports = __toCommonJS(videoPlayerHelper_exports); +function getShowStatus(isLoadingVideo, isEnd, isError) { + let status = null; + if (isLoadingVideo) { + status = "LOADING"; + } + if (isError) { + status = "ERROR"; + } + if (isEnd) { + status = "END"; + } + return status; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getShowStatus +}); diff --git a/packages/meta/lib/iconfont/iconfont.css b/packages/meta/lib/iconfont/iconfont.css new file mode 100644 index 0000000..8bde390 --- /dev/null +++ b/packages/meta/lib/iconfont/iconfont.css @@ -0,0 +1,1679 @@ +@font-face { + font-family: iconfont; /* Project id 1739270 */ + src: url('iconfont.woff2?t=1689583241972') format('woff2'), + url('iconfont.woff?t=1689583241972') format('woff'), + url('iconfont.ttf?t=1689583241972') format('truetype'); +} + +.iconfont { + font-family: iconfont !important; + font-size: 16px; + font-style: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.icon-danganxiangqing_hangweifenxi::before { + content: "\e78d"; +} + +.icon-danganxiangqing_shujuganzhi::before { + content: "\e78e"; +} + +.icon-danganxiangqing_huodongguiji::before { + content: "\e78f"; +} + +.icon-danganxiangqing_jibenxinxi::before { + content: "\e7ea"; +} + +.icon-danganxiangqing_fushuwupin::before { + content: "\e7eb"; +} + +.icon-danganxiangqing_jizhanyingyong::before { + content: "\e7ec"; +} + +.icon-jiarudanganku::before { + content: "\e787"; +} + +.icon-dangankunor::before { + content: "\e793"; +} + +.icon-bukongrenwuselect::before { + content: "\e799"; +} + +.icon-bukongrenwunor1::before { + content: "\e79a"; +} + +.icon-dangankuselect::before { + content: "\e79b"; +} + +.icon-jizhanfanor::before { + content: "\e79c"; +} + +.icon-feijidongchechaxunnor::before { + content: "\e79d"; +} + +.icon-jidongchechaxunselect::before { + content: "\e79e"; +} + +.icon-a-lixianfenxiselect2::before { + content: "\e7a1"; +} + +.icon-huisufenxiselect::before { + content: "\e7a2"; +} + +.icon-jizhanfaselect::before { + content: "\e7a3"; +} + +.icon-mubiaojiansuonor::before { + content: "\e7ae"; +} + +.icon-lurenkuselect::before { + content: "\e7b1"; +} + +.icon-shujujiashicangselect::before { + content: "\e7b2"; +} + +.icon-shishijiexiselect::before { + content: "\e7b4"; +} + +.icon-shishijiexinor::before { + content: "\e7b9"; +} + +.icon-jidongchechaxunnor::before { + content: "\e7c1"; +} + +.icon-lurenkunor1::before { + content: "\e7cf"; +} + +.icon-mubiaotezhengchaxunnor::before { + content: "\e7e1"; +} + +.icon-yujingjiluselect::before { + content: "\e7e2"; +} + +.icon-mubiaotezhengchaxunselect::before { + content: "\e7e3"; +} + +.icon-feijidongchechaxunselect::before { + content: "\e7e4"; +} + +.icon-yujingjilunor::before { + content: "\e7e5"; +} + +.icon-lixianfenxiselect::before { + content: "\e7e6"; +} + +.icon-huisufenxinor::before { + content: "\e7e7"; +} + +.icon-shujujiashicangnor::before { + content: "\e7e8"; +} + +.icon-mubiaojiansuoselect::before { + content: "\e7e9"; +} + +.icon-kuangxuangongju::before { + content: "\e796"; +} + +.icon-fengniao::before { + content: "\e792"; +} + +.icon-zhankai::before { + content: "\e790"; +} + +.icon-shouqi::before { + content: "\e791"; +} + +.icon-shijian::before { + content: "\e786"; +} + +.icon-dingwei2::before { + content: "\e613"; +} + +.icon-renyuan::before { + content: "\e784"; +} + +.icon-houtai::before { + content: "\e785"; +} + +.icon-zuo::before { + content: "\e781"; +} + +.icon-you::before { + content: "\e783"; +} + +.icon-kakou::before { + content: "\e780"; +} + +.icon-yujing1::before { + content: "\e77e"; +} + +.icon-yuan2::before { + content: "\e77d"; +} + +.icon-moxingpengzhuang::before { + content: "\e777"; +} + +.icon-moxingpengzhuangnor::before { + content: "\e778"; +} + +.icon-lurenku::before { + content: "\e77b"; +} + +.icon-lurenkunor::before { + content: "\e77c"; +} + +.icon-shiming::before { + content: "\e776"; +} + +.icon-suoxiao2::before { + content: "\e774"; +} + +.icon-fangda1::before { + content: "\e775"; +} + +.icon-guanbi2::before { + content: "\e772"; +} + +.icon-fanhui1::before { + content: "\e773"; +} + +.icon-xiansuomopai::before { + content: "\e76f"; +} + +.icon-xiansuomopainor::before { + content: "\e76e"; +} + +.icon-zhajiyujing::before { + content: "\e770"; +} + +.icon-zhajiyujingnor::before { + content: "\e771"; +} + +.icon-zhuizongpeizhi::before { + content: "\e76c"; +} + +.icon-zhuizongpeizhinor::before { + content: "\e76d"; +} + +.icon-dapingqiehuan::before { + content: "\e76b"; +} + +.icon-xuanze::before { + content: "\e769"; +} + +.icon-shaixuan1::before { + content: "\e76a"; +} + +.icon-chekashebei::before { + content: "\e764"; +} + +.icon-imsishebei::before { + content: "\e765"; +} + +.icon-xingtishebei::before { + content: "\e766"; +} + +.icon-renlianshebei::before { + content: "\e767"; +} + +.icon-wifishebei::before { + content: "\e768"; +} + +.icon-a-miaozhun2::before { + content: "\e762"; +} + +.icon-a-bianzu19::before { + content: "\e763"; +} + +.icon-fanye::before { + content: "\e75e"; +} + +.icon-shenfenzheng::before { + content: "\e75f"; +} + +.icon-dizhi::before { + content: "\e760"; +} + +.icon-guanbi::before { + content: "\e761"; +} + +.icon-dianwei1::before { + content: "\e75b"; +} + +.icon-weikakou::before { + content: "\e757"; +} + +.icon-weikakounor::before { + content: "\e758"; +} + +.icon-changsuoma::before { + content: "\e759"; +} + +.icon-changsuomanor::before { + content: "\e75a"; +} + +.icon-yujing::before { + content: "\e756"; +} + +.icon-jiansuonor::before { + content: "\e747"; +} + +.icon-tonghangrenfenxinor1::before { + content: "\e748"; +} + +.icon-zhinengyanpannor::before { + content: "\e749"; +} + +.icon-bukongyujingnor::before { + content: "\e74a"; +} + +.icon-bukongrenwunor::before { + content: "\e74b"; +} + +.icon-dianziditunor::before { + content: "\e754"; +} + +.icon-zhuizongnor1::before { + content: "\e755"; +} + +.icon-zhuizong1::before { + content: "\e746"; +} + +.icon-bukongrenwu3::before { + content: "\e74c"; +} + +.icon-dianziditu::before { + content: "\e74d"; +} + +.icon-bukongyujing::before { + content: "\e750"; +} + +.icon-tonghangrenfenxi1::before { + content: "\e751"; +} + +.icon-zhinengyanpan::before { + content: "\e752"; +} + +.icon-jiansuo1::before { + content: "\e753"; +} + +.icon-kaiqijulei::before { + content: "\e745"; +} + +.icon-tongbu::before { + content: "\e744"; +} + +.icon-tonghangrenfenxi::before { + content: "\e743"; +} + +.icon-tonghangrenfenxinor::before { + content: "\e742"; +} + +.icon-jizhanyingyong::before { + content: "\e741"; +} + +.icon-haikangrenlianbukongnor::before { + content: "\e740"; +} + +.icon-haikangrenlianbukong::before { + content: "\e73f"; +} + +.icon-tuozhanshouduantishi::before { + content: "\e73e"; +} + +.icon-fanhuimopailiebiao::before { + content: "\e73d"; +} + +.icon-toukuijiancenor::before { + content: "\e73c"; +} + +.icon-toukuijiance::before { + content: "\e718"; +} + +.icon-zhuixing::before { + content: "\e717"; +} + +.icon-tishi4::before { + content: "\e73b"; +} + +.icon-a-shaixuanfeiji::before { + content: "\e733"; +} + +.icon-a-zidongtiaozhengfanweifeiji::before { + content: "\e73a"; +} + +.icon-heziyunwei::before { + content: "\e739"; +} + +.icon-qiehuan::before { + content: "\e738"; +} + +.icon-disanfangxiaoxinor::before { + content: "\e737"; +} + +.icon-disanfangxiaoxi::before { + content: "\e736"; +} + +.icon-daohang::before { + content: "\e735"; +} + +.icon-yonghu::before { + content: "\e734"; +} + +.icon-feiji::before { + content: "\e732"; +} + +.icon-jieshuzhuizong::before { + content: "\e730"; +} + +.icon-huisuzhoubian::before { + content: "\e731"; +} + +.icon-jixuzhuizong::before { + content: "\e72d"; +} + +.icon-tiaozhengfanwei::before { + content: "\e72e"; +} + +.icon-jiansuo::before { + content: "\e72f"; +} + +.icon-guiji::before { + content: "\e72c"; +} + +.icon-jichuxinxi::before { + content: "\e72b"; +} + +.icon-danganzhaiyao::before { + content: "\e72a"; +} + +.icon-jingzhunbukongicon_on::before { + content: "\e728"; +} + +.icon-jingzhunbukongicon_off::before { + content: "\e729"; +} + +.icon-tiaozhuan::before { + content: "\e727"; +} + +.icon-shezhi::before { + content: "\e726"; +} + +.icon-bangzhu1::before { + content: "\e725"; +} + +.icon-shuaxin1::before { + content: "\e724"; +} + +.icon-duosucaibeifen::before { + content: "\e722"; +} + +.icon-duosucai::before { + content: "\e723"; +} + +.icon-shujutongji::before { + content: "\e721"; +} + +.icon-renlian::before { + content: "\e71c"; +} + +.icon-xingti::before { + content: "\e71d"; +} + +.icon-jidongche::before { + content: "\e71e"; +} + +.icon-huisufenxi4::before { + content: "\e71f"; +} + +.icon-lixianfenxi4::before { + content: "\e720"; +} + +.icon-feijidongche::before { + content: "\e71b"; +} + +.icon-shujudaping::before { + content: "\e71a"; +} + +.icon-peizhisuanfa::before { + content: "\e719"; +} + +.icon-zhuizong::before { + content: "\e715"; +} + +.icon-zhuizongnor::before { + content: "\e716"; +} + +.icon-dianwei::before { + content: "\e714"; +} + +.icon-Container::before { + content: "\e713"; +} + +.icon-Attachment::before { + content: "\e712"; +} + +.icon-cha::before { + content: "\e711"; +} + +.icon-gou::before { + content: "\e710"; +} + +.icon-daoru::before { + content: "\e70f"; +} + +.icon-quanxijiansuo::before { + content: "\e70e"; +} + +.icon-chakanjiankong::before { + content: "\e70c"; +} + +.icon-tishi3::before { + content: "\e70d"; +} + +.icon-heiyemoshi::before { + content: "\e70b"; +} + +.icon-zhengchangmoshi::before { + content: "\e70a"; +} + +.icon-dingwei1::before { + content: "\e709"; +} + +.icon-paixu::before { + content: "\e708"; +} + +.icon-tianjiayuan::before { + content: "\e707"; +} + +.icon-juleidangankunor::before { + content: "\e705"; +} + +.icon-juleidanganku::before { + content: "\e706"; +} + +.icon-guanlian::before { + content: "\e704"; +} + +.icon-renlianbiaozhu::before { + content: "\e703"; +} + +.icon-juleijieguo::before { + content: "\e6ec"; +} + +.icon-juleirenwunor::before { + content: "\e6fb"; +} + +.icon-juleijieguonor::before { + content: "\e701"; +} + +.icon-juleirenwu::before { + content: "\e702"; +} + +.icon-zhongzhi3::before { + content: "\e8ff"; +} + +.icon-xuanzhuan1::before { + content: "\e6fd"; +} + +.icon-shuangmubiaozhu1::before { + content: "\e700"; +} + +.icon-shoudongkuangxuan::before { + content: "\e6f9"; +} + +.icon-zanting1::before { + content: "\e6fe"; +} + +.icon-zhongzhi1::before { + content: "\e6ff"; +} + +.icon-shoudong::before { + content: "\e6fa"; +} + +.icon-zidong::before { + content: "\e6fc"; +} + +.icon-zhenduan::before { + content: "\e6f8"; +} + +.icon-Check-Circle-Fill1::before { + content: "\e6f3"; +} + +.icon-Info--Circle-Fill::before { + content: "\e6f4"; +} + +.icon-Close-Circle-Fill::before { + content: "\e6f5"; +} + +.icon-Warning-Circle-Fill::before { + content: "\e6f6"; +} + +.icon-Question-Circle-Fill::before { + content: "\e6f7"; +} + +.icon-zancunjia::before { + content: "\e6f2"; +} + +.icon-Check-Circle-Fill::before { + content: "\e6f1"; +} + +.icon-tupianji::before { + content: "\e6f0"; +} + +.icon-quanping1::before { + content: "\e6ed"; +} + +.icon-yinliang::before { + content: "\e6ee"; +} + +.icon-suoxiao1::before { + content: "\e6ef"; +} + +.icon-home::before { + content: "\e6eb"; +} + +.icon-zuixiaohua::before { + content: "\e6e9"; +} + +.icon-zuidahua::before { + content: "\e6ea"; +} + +.icon-biaozhunhua::before { + content: "\e6e6"; +} + +.icon-julei::before { + content: "\e6e5"; +} + +.icon-bianzu::before { + content: "\e6e7"; +} + +.icon-bianzu3::before { + content: "\e6e8"; +} + +.icon-bianzu7::before { + content: "\e6e3"; +} + +.icon-bianzu2::before { + content: "\e6e4"; +} + +.icon-kapianqiehuan::before { + content: "\e6e2"; +} + +.icon-duobianxing1::before { + content: "\e6e0"; +} + +.icon-fang1::before { + content: "\e6e1"; +} + +.icon-yuan1::before { + content: "\e6df"; +} + +.icon-cejuli::before { + content: "\e6de"; +} + +.icon-wanggekuangxuannor::before { + content: "\e6dc"; +} + +.icon-lujingkuangxuannor::before { + content: "\e6dd"; +} + +.icon-chuansuo::before { + content: "\e6db"; +} + +.icon-bianyuanhezinor::before { + content: "\e6d8"; +} + +.icon-wujiankuhov::before { + content: "\e6d9"; +} + +.icon-caozuorizhinor::before { + content: "\e6da"; +} + +.icon-collect_dot::before { + content: "\e619"; +} + +.icon-chuxiandingweibg::before { + content: "\e6d4"; +} + +.icon-chuxiandingweiicon::before { + content: "\e6d5"; +} + +.icon-shexiangtoudingweibg::before { + content: "\e6d6"; +} + +.icon-shexiangtoudingweiicon::before { + content: "\e6d7"; +} + +.icon-xiafajieguo::before { + content: "\e6d2"; +} + +.icon-daochu1::before { + content: "\e6d3"; +} + +.icon-zuijinchuxian::before { + content: "\e6cc"; +} + +.icon-leijizhuapai::before { + content: "\e6d0"; +} + +.icon-yichangshijian::before { + content: "\e6d1"; +} + +.icon-dingwei::before { + content: "\e6cb"; +} + +.icon-tupian::before { + content: "\e6ad"; +} + +.icon-wenti::before { + content: "\e6ac"; +} + +.icon-lixian1::before { + content: "\e6ab"; +} + +.icon-yichang::before { + content: "\e6a8"; +} + +.icon-zhuixing-xiugaidianwei::before { + content: "\e6a7"; +} + +.icon-wenhao1::before { + content: "\e69e"; +} + +.icon-ditu_dingwei::before { + content: "\e69d"; +} + +.icon-ditu_fangda::before { + content: "\e689"; +} + +.icon-ditu_suoxiao::before { + content: "\e69a"; +} + +.icon-chakanbukongrenwu::before { + content: "\e688"; +} + +.icon-lietu::before { + content: "\e687"; +} + +.icon-zhongzhi::before { + content: "\e67e"; +} + +.icon-xialada::before { + content: "\e67f"; +} + +.icon-zhinengguanlian_xingti::before { + content: "\e67b"; +} + +.icon-zhinengguanlian_renlian::before { + content: "\e67c"; +} + +.icon-xiajiantou::before { + content: "\e75c"; +} + +.icon-zhinengguanlian_xiaojiantou::before { + content: "\e67d"; +} + +.icon-zhinengguanlian_jiantou::before { + content: "\e67a"; +} + +.icon-shangjiantou::before { + content: "\e75d"; +} + +.icon-banbenxinxi::before { + content: "\e679"; +} + +.icon-wenhao::before { + content: "\e61f"; +} + +.icon-bianjirenyuan::before { + content: "\e7e0"; +} + +.icon-tishi2::before { + content: "\e7df"; +} + +.icon-shexiangji2::before { + content: "\e7de"; +} + +.icon-guijizhuizong::before { + content: "\e7dd"; +} + +.icon-jiezhen1::before { + content: "\e7dc"; +} + +.icon-tianjiaguijihuisu::before { + content: "\e7db"; +} + +.icon-tingzhi::before { + content: "\e7cd"; +} + +.icon-baoweiquan::before { + content: "\e7ce"; +} + +.icon-shangchuanshipin::before { + content: "\e7d0"; +} + +.icon-yidong::before { + content: "\e7d1"; +} + +.icon-chuangjianxinbukong1::before { + content: "\e7d2"; +} + +.icon-yichu1::before { + content: "\e7d3"; +} + +.icon-tishi1::before { + content: "\e7d4"; +} + +.icon-VS::before { + content: "\e7d5"; +} + +.icon-quanjuzonglan::before { + content: "\e7d6"; +} + +.icon-chakanfenxirenwu1::before { + content: "\e7d7"; +} + +.icon-xiaoxi::before { + content: "\e7d8"; +} + +.icon-yonghuming::before { + content: "\e7d9"; +} + +.icon-tuichu::before { + content: "\e7da"; +} + +.icon-guijizhuizongnor::before { + content: "\e7cb"; +} + +.icon-guijizhuizong2::before { + content: "\e7cc"; +} + +.icon-bukongrenwu1::before { + content: "\e7b7"; +} + +.icon-shexiangji::before { + content: "\e7b8"; +} + +.icon-yujingditu::before { + content: "\e7ba"; +} + +.icon-lixianfenxi2::before { + content: "\e7bb"; +} + +.icon-yuanguanli1::before { + content: "\e7bc"; +} + +.icon-danganku::before { + content: "\e7bd"; +} + +.icon-huisufenxi2::before { + content: "\e7be"; +} + +.icon-kuneijiansuo::before { + content: "\e7bf"; +} + +.icon-jiegouhuachaxun::before { + content: "\e7c0"; +} + +.icon-bukongrenwu2::before { + content: "\e7c2"; +} + +.icon-yuanguanli2::before { + content: "\e7c3"; +} + +.icon-shexiangji1::before { + content: "\e7c4"; +} + +.icon-kuneijiansuo1::before { + content: "\e7c5"; +} + +.icon-lixianfenxi3::before { + content: "\e7c6"; +} + +.icon-danganku1::before { + content: "\e7c7"; +} + +.icon-yujingditu1::before { + content: "\e7c8"; +} + +.icon-huisufenxi3::before { + content: "\e7c9"; +} + +.icon-jiegouhuachaxunnor::before { + content: "\e7ca"; +} + +.icon-chuangjianxinbukong::before { + content: "\e7b6"; +} + +.icon-kuangxuan::before { + content: "\e77f"; +} + +.icon-gaojishaixuan::before { + content: "\e779"; +} + +.icon-gaojishaixuanshouqi::before { + content: "\e77a"; +} + +.icon-bukongrenwu::before { + content: "\e7b5"; +} + +.icon-riqi::before { + content: "\e74f"; +} + +.icon-shijianqiehuan::before { + content: "\e797"; +} + +.icon-shouquan1::before { + content: "\e7b3"; +} + +.icon-video-play::before { + content: "\e653"; +} + +.icon-shishifenxi::before { + content: "\e7af"; +} + +.icon-chakanfenxirenwu::before { + content: "\e7b0"; +} + +.icon-jiegouhuafenxi::before { + content: "\e7ad"; +} + +.icon-tianjiaguiji2::before { + content: "\e6aa"; +} + +.icon-tianjiajiansuomubiao::before { + content: "\e6b0"; +} + +.icon-add::before { + content: "\e661"; +} + +.icon-didian::before { + content: "\e798"; +} + +.icon-bofanghov::before { + content: "\e79f"; +} + +.icon-bofang3::before { + content: "\e7a0"; +} + +.icon-jinggao::before { + content: "\e788"; +} + +.icon-tishi::before { + content: "\e789"; +} + +.icon-bangzhu::before { + content: "\e78a"; +} + +.icon-guanbi1::before { + content: "\e78b"; +} + +.icon-chenggong::before { + content: "\e78c"; +} + +.icon-qianwang::before { + content: "\e7ac"; +} + +.icon-shouquan::before { + content: "\e7ab"; +} + +.icon-jingweidu::before { + content: "\e7aa"; +} + +.icon-shanchu1::before { + content: "\e74e"; +} + +.icon-daochu::before { + content: "\e782"; +} + +.icon-ziyuanguanli::before { + content: "\e7a4"; +} + +.icon-fuwuqishouquan::before { + content: "\e7a5"; +} + +.icon-xiugaimima::before { + content: "\e7a6"; +} + +.icon-zhanghaoguanli::before { + content: "\e7a7"; +} + +.icon-suanlipeie::before { + content: "\e7a8"; +} + +.icon-VMSpeizhi::before { + content: "\e7a9"; +} + +.icon-tianjia1::before { + content: "\e794"; +} + +.icon-yichu::before { + content: "\e795"; +} + +.icon-lujing::before { + content: "\e6cf"; +} + +.icon-jiankongxinxi::before { + content: "\e6c8"; +} + +.icon-fanwei::before { + content: "\e6c9"; +} + +.icon-anfadidian::before { + content: "\e6ca"; +} + +.icon-gongjuxiang::before { + content: "\e6cd"; +} + +.icon-gongjuxiangguanbi1::before { + content: "\e6ce"; +} + +.icon-jiezhen::before { + content: "\e6c2"; +} + +.icon-huisufenxi1::before { + content: "\e6c6"; +} + +.icon-huisufenxi::before { + content: "\e6c7"; +} + +.icon-tianjiashipinwenjian1::before { + content: "\e6c5"; +} + +.icon-jiazaishibai::before { + content: "\e6c3"; +} + +.icon-shuaxin::before { + content: "\e6c4"; +} + +.icon-quanping::before { + content: "\e6c0"; +} + +.icon-quxiaoquanping::before { + content: "\e6c1"; +} + +.icon-shipinbofang::before { + content: "\e6be"; +} + +.icon-shipinzanting::before { + content: "\e6bf"; +} + +.icon-lixianguiji::before { + content: "\e6bd"; +} + +.icon-lixian::before { + content: "\e6bc"; +} + +.icon-xiaojiaobiao::before { + content: "\e6bb"; +} + +.icon-shangchuan1::before { + content: "\e6ba"; +} + +.icon-tianjiaweijiansuoduixiang::before { + content: "\e6b8"; +} + +.icon-tianjiaweijiansuojilu::before { + content: "\e6b9"; +} + +.icon-lixianfenxi1::before { + content: "\e6b7"; +} + +.icon-kuaisujiansuohov::before { + content: "\e6b5"; +} + +.icon-kuaisujiansuo1::before { + content: "\e6b6"; +} + +.icon-kuaisujiansuo::before { + content: "\e6b4"; +} + +.icon-yuanguanli::before { + content: "\e6b1"; +} + +.icon-shexiangtou::before { + content: "\e6b2"; +} + +.icon-lixianfenxi::before { + content: "\e6b3"; +} + +.icon-filter::before { + content: "\e61a"; +} + +.icon-tianjiaweizhuizongduixiang2::before { + content: "\e6af"; +} + +.icon-tianjiaweizhuizongduixiang1::before { + content: "\e6ae"; +} + +.icon-baocun1::before { + content: "\e6a9"; +} + +.icon-tianjiashipinwenjianjia::before { + content: "\e6a5"; +} + +.icon-tianjiashipinwenjian::before { + content: "\e6a6"; +} + +.icon-ditu::before { + content: "\e6a4"; +} + +.icon-xinjianshexiangtou::before { + content: "\e6a3"; +} + +.icon-lishihuisu::before { + content: "\e6a2"; +} + +.icon-decoyitianjiaweiguiji::before { + content: "\e69f"; +} + +.icon-bofangqiehuan::before { + content: "\e6a0"; +} + +.icon-tianjia::before { + content: "\e6a1"; +} + +.icon-baocun::before { + content: "\e698"; +} + +.icon-gongjuxiangguanbi::before { + content: "\e699"; +} + +.icon-shangchuan::before { + content: "\e69b"; +} + +.icon-gongjuxiang1::before { + content: "\e69c"; +} + +.icon-logo::before { + content: "\e692"; +} + +.icon-setting::before { + content: "\e627"; +} + +.icon-user::before { + content: "\e628"; +} + +.icon-quit::before { + content: "\e629"; +} + +.icon-arrowzhankaimeixuanzhong::before { + content: "\e693"; +} + +.icon-arrowzhankaixuanzhong::before { + content: "\e694"; +} + +.icon-xuanzexuanzhong::before { + content: "\e695"; +} + +.icon-xuanzebanxuan::before { + content: "\e696"; +} + +.icon-xuanzenor::before { + content: "\e697"; +} + +.icon-shaixuanguanbinor::before { + content: "\e691"; +} + +.icon-gengduo::before { + content: "\e68e"; +} + +.icon-youzhankai::before { + content: "\e68f"; +} + +.icon-zuoshouqi::before { + content: "\e690"; +} + +.icon-yuan::before { + content: "\e68a"; +} + +.icon-duobianxing::before { + content: "\e68b"; +} + +.icon-fang::before { + content: "\e68c"; +} + +.icon-ceju::before { + content: "\e68d"; +} + +.icon-shishizhuizong1::before { + content: "\e683"; +} + +.icon-guijihuisu1::before { + content: "\e684"; +} + +.icon-tianjiaguiji::before { + content: "\e685"; +} + +.icon-yichuguiji::before { + content: "\e686"; +} + +.icon-fangda::before { + content: "\e680"; +} + +.icon-suoxiao::before { + content: "\e681"; +} + +.icon-xiazai::before { + content: "\e682"; +} + +.icon-fanhui::before { + content: "\e678"; +} + +.icon-sousuo::before { + content: "\e669"; +} + +.icon-quxiaoxuanzhong::before { + content: "\e66a"; +} + +.icon-piliangxuanzenor::before { + content: "\e66b"; +} + +.icon-kaiqifenxi::before { + content: "\e66c"; +} + +.icon-quxiaofenxi::before { + content: "\e66d"; +} + +.icon-shaixuan::before { + content: "\e66e"; +} + +.icon-dangan::before { + content: "\e66f"; +} + +.icon-bofang::before { + content: "\e670"; +} + +.icon-zanting::before { + content: "\e671"; +} + +.icon-shanchu::before { + content: "\e672"; +} + +.icon-tianjiaweizhuizongduixiang::before { + content: "\e673"; +} + +.icon-chakandatu::before { + content: "\e674"; +} + +.icon-jiansuojilu::before { + content: "\e675"; +} + +.icon-yuzhi::before { + content: "\e676"; +} + +.icon-chakanxiangqing::before { + content: "\e677"; +} + +.icon-guijihuisu::before { + content: "\e65c"; +} + +.icon-dianweipeizhinor::before { + content: "\e65d"; +} + +.icon-yirenyidang::before { + content: "\e65e"; +} + +.icon-tongbanfenxi::before { + content: "\e65f"; +} + +.icon-qiehuanzuo::before { + content: "\e662"; +} + +.icon-qiehuanyou::before { + content: "\e663"; +} + +.icon-tingzhidengdai::before { + content: "\e664"; +} + +.icon-yiguanbi::before { + content: "\e665"; +} + +.icon-danchuangguanbi::before { + content: "\e666"; +} + +.icon-lishijilu::before { + content: "\e64a"; +} + +.icon-xuanzhuan::before { + content: "\e648"; +} + +.icon-qingchu::before { + content: "\e649"; +} + +.icon-dangantianjia::before { + content: "\e63d"; +} + +.icon-bianji::before { + content: "\e63e"; +} + +.icon-fullscreen::before { + content: "\e63b"; +} + +.icon-cancle_fullscreen::before { + content: "\e63c"; +} + +.icon-quanyujiansuo_nor::before { + content: "\e639"; +} + +.icon-guijihuisu_nor::before { + content: "\e63a"; +} + diff --git a/packages/meta/lib/iconfont/iconfont.js b/packages/meta/lib/iconfont/iconfont.js new file mode 100644 index 0000000..16d543e --- /dev/null +++ b/packages/meta/lib/iconfont/iconfont.js @@ -0,0 +1,36 @@ +// src/iconfont/iconfont.js +window._iconfont_svg_string_1739270 = '', function(h) { + var a = (a = document.getElementsByTagName("script"))[a.length - 1], l = a.getAttribute("data-injectcss"), a = a.getAttribute("data-disable-injectsvg"); + if (!a) { + var i, c, o, t, z, v = function(a2, l2) { + l2.parentNode.insertBefore(a2, l2); + }; + if (l && !h.__iconfont__svg__cssinject__) { + h.__iconfont__svg__cssinject__ = true; + try { + document.write(""); + } catch (a2) { + console && console.log(a2); + } + } + i = function() { + var a2, l2 = document.createElement("div"); + l2.innerHTML = h._iconfont_svg_string_1739270, (l2 = l2.getElementsByTagName("svg")[0]) && (l2.setAttribute("aria-hidden", "true"), l2.style.position = "absolute", l2.style.width = 0, l2.style.height = 0, l2.style.overflow = "hidden", l2 = l2, (a2 = document.body).firstChild ? v(l2, a2.firstChild) : a2.appendChild(l2)); + }, document.addEventListener ? ~["complete", "loaded", "interactive"].indexOf(document.readyState) ? setTimeout(i, 0) : (c = function() { + document.removeEventListener("DOMContentLoaded", c, false), i(); + }, document.addEventListener("DOMContentLoaded", c, false)) : document.attachEvent && (o = i, t = h.document, z = false, p(), t.onreadystatechange = function() { + "complete" == t.readyState && (t.onreadystatechange = null, m()); + }); + } + function m() { + z || (z = true, o()); + } + function p() { + try { + t.documentElement.doScroll("left"); + } catch (a2) { + return void setTimeout(p, 50); + } + m(); + } +}(window); diff --git a/packages/meta/lib/iconfont/iconfont.ttf b/packages/meta/lib/iconfont/iconfont.ttf new file mode 100644 index 0000000..0043e6a Binary files /dev/null and b/packages/meta/lib/iconfont/iconfont.ttf differ diff --git a/packages/meta/lib/iconfont/iconfont.woff b/packages/meta/lib/iconfont/iconfont.woff new file mode 100644 index 0000000..84f32bb Binary files /dev/null and b/packages/meta/lib/iconfont/iconfont.woff differ diff --git a/packages/meta/lib/iconfont/iconfont.woff2 b/packages/meta/lib/iconfont/iconfont.woff2 new file mode 100644 index 0000000..8173340 Binary files /dev/null and b/packages/meta/lib/iconfont/iconfont.woff2 differ diff --git a/packages/meta/lib/iconfont/index.d.ts b/packages/meta/lib/iconfont/index.d.ts index e769332..fcafc45 100644 --- a/packages/meta/lib/iconfont/index.d.ts +++ b/packages/meta/lib/iconfont/index.d.ts @@ -1,4 +1,5 @@ import React from 'react'; +import './iconfont.css'; interface IconFontProps { styles?: React.CSSProperties; icon?: string; diff --git a/packages/meta/lib/iconfont/index.js b/packages/meta/lib/iconfont/index.js index 900a9ac..c1cfc88 100644 --- a/packages/meta/lib/iconfont/index.js +++ b/packages/meta/lib/iconfont/index.js @@ -34,6 +34,7 @@ __export(iconfont_exports, { module.exports = __toCommonJS(iconfont_exports); var import_react = __toESM(require("react")); var import_classnames = __toESM(require("classnames")); +var import_iconfont = require("./iconfont.css"); var IconFont = (props) => { const { title = "", diff --git a/packages/meta/lib/index.d.ts b/packages/meta/lib/index.d.ts index 241716b..e0961ce 100644 --- a/packages/meta/lib/index.d.ts +++ b/packages/meta/lib/index.d.ts @@ -1,3 +1,5 @@ export { default as doubleClick } from './doubleClick'; export { default as Icon } from './iconfont'; -export { default as ImagePreview } from './ImagePreview'; +export { default as CompareImage } from './CompareImage'; +export { default as BigImagePreview } from './BigImagePreview'; +export { default as VideoPlayer } from './VideoPlayer'; diff --git a/packages/meta/lib/index.js b/packages/meta/lib/index.js index f9d0355..bbf718b 100644 --- a/packages/meta/lib/index.js +++ b/packages/meta/lib/index.js @@ -29,17 +29,23 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.tsx var src_exports = {}; __export(src_exports, { + BigImagePreview: () => import_BigImagePreview.default, + CompareImage: () => import_CompareImage.default, Icon: () => import_iconfont.default, - ImagePreview: () => import_ImagePreview.default, + VideoPlayer: () => import_VideoPlayer.default, doubleClick: () => import_doubleClick.default }); module.exports = __toCommonJS(src_exports); var import_doubleClick = __toESM(require("./doubleClick")); var import_iconfont = __toESM(require("./iconfont")); -var import_ImagePreview = __toESM(require("./ImagePreview")); +var import_CompareImage = __toESM(require("./CompareImage")); +var import_BigImagePreview = __toESM(require("./BigImagePreview")); +var import_VideoPlayer = __toESM(require("./VideoPlayer")); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { + BigImagePreview, + CompareImage, Icon, - ImagePreview, + VideoPlayer, doubleClick }); diff --git a/packages/meta/lib/utils/constants.d.ts b/packages/meta/lib/utils/constants.d.ts new file mode 100644 index 0000000..f9bb021 --- /dev/null +++ b/packages/meta/lib/utils/constants.d.ts @@ -0,0 +1,12 @@ +export declare const CROP_TYPE: { + CUSTOM: string; + AUTO: string; +}; +export declare const defaultAlignOption: { + points: string[]; + offset: number[]; + overflow: { + adjustX: boolean; + adjustY: boolean; + }; +}; diff --git a/packages/meta/lib/utils/constants.js b/packages/meta/lib/utils/constants.js new file mode 100644 index 0000000..caa5deb --- /dev/null +++ b/packages/meta/lib/utils/constants.js @@ -0,0 +1,42 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils/constants.ts +var constants_exports = {}; +__export(constants_exports, { + CROP_TYPE: () => CROP_TYPE, + defaultAlignOption: () => defaultAlignOption +}); +module.exports = __toCommonJS(constants_exports); +var CROP_TYPE = { + CUSTOM: "CSUTOM", + AUTO: "AUTO" +}; +var defaultAlignOption = { + points: ["bl", "br"], + offset: [6, 0], + overflow: { + adjustX: true, + adjustY: true + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + CROP_TYPE, + defaultAlignOption +}); diff --git a/packages/meta/package.json b/packages/meta/package.json index 511d81a..9ffc250 100644 --- a/packages/meta/package.json +++ b/packages/meta/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/meta", - "version": "0.2.4", + "version": "0.3.0", "description": "原子组件", "keywords": [ "meta", diff --git a/packages/meta/src/BigImagePreview/BigImagePreview.tsx b/packages/meta/src/BigImagePreview/BigImagePreview.tsx new file mode 100644 index 0000000..f7fbf93 --- /dev/null +++ b/packages/meta/src/BigImagePreview/BigImagePreview.tsx @@ -0,0 +1,562 @@ +import React, { useEffect, ReactElement, useState, useCallback, useRef, useImperativeHandle } from 'react'; +import classNames from 'classnames'; +import { useLatest } from '@zhst/hooks'; +import { + get, + pick, + isNull, + generateImg, + dataURLToBlob, + getOdRect, + getExtendRect, + getTransformRect, + getRotateImg, + getTransforms, + addEventListenerWrapper, + upload, + getFileByRect +} from '@zhst/func'; +import Align from 'rc-align'; +import { Button, Empty } from 'antd'; +import { type Rect, type IScreenshotButtonProp, type ODRECT, type AlignType, type ViewOption, type IOdRectOrigin, AlgorithmVersion } from '@zhst/types' +import Icon from '../iconfont'; +import { + Cropper, + Viewer, + EVENT_VIEWER_TRANSFORM_CHANGE, + EVENT_VIEWER_READY, + EVENT_CROP_START, + EVENT_CROP_END, +} from '../ImageEditor'; +import BtnGroup from './components/BtnGroup'; +import './index.less' +import getScreenshotButtonRender from './components/ScreenhotButtons'; +import { defaultAlignOption, CROP_TYPE } from '../utils/constants' + +const componentName = `zhst-image__img-view`; + +export interface ImgViewProps extends React.HTMLAttributes { + dataSource: Array<{ + url?: string + imageKey: string + attachImg?: Array<{ label: string; url: string }>; // 缩略图列表 + odRect?: Rect + score?: number + showScore?: boolean + cameraPosition?: string + time?: string | number + objects: any[] + }> + showAttachImgLabel: boolean; // 是否显示缩略图 + showOpt: boolean; // 是否显示操作面板 + width?: string | number; // 画布宽度 + height?: string | number; // 画布高度 + /* 截图渲染 */ + screenshotButtonAlign: AlignType; + screenshotButtonRender: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; + hideLeftTopBtn?: boolean; + showScore?: boolean // 是否显示相似度 + viewOption?: ViewOption; + objects: IOdRectOrigin[] // 图片人物框选 +} +export interface ImgViewRef { + /* 图片实例 */ + imgInsRef: React.MutableRefObject; + /* 切换编辑模式 */ + setShowCrop: React.Dispatch>; +} + +const cropBtnDataSource = [ + { + key: 'close', + icon: 'icon-danchuangguanbi', + title: '退出', + }, + { + key: 'autoCrop', + icon: 'icon-zidong', + title: '智能框选', + }, + { + key: 'customCrop', + icon: 'icon-shoudong', + title: '手动框选', + }, +]; + +const operateBtnDataSource = [ + { + key: 'zoomOut', + icon: 'icon-fangda', + title: '放大', + }, + { + key: 'zoomIn', + icon: 'icon-suoxiao', + title: '缩小', + }, + { + key: 'reset', + icon: 'icon-zhongzhi3', + title: '重置图片', + }, +]; + +export const BigImagePreview = React.forwardRef((props, ref) => { + const { + dataSource = [], + width, + height, + showScore = true, + objects = [], + showOpt = false, + showAttachImgLabel = true, + screenshotButtonAlign = defaultAlignOption, + screenshotButtonRender = getScreenshotButtonRender({ + onBigImageActionClick: () => {}, + disableBtn: [], + }), + hideLeftTopBtn = true, + viewOption = {} + } = props; + const imgContainerRef = React.useRef(null); + const [isReady, setIsReady] = useState(false); + const [currentIndex, setCurrentIndex] = useState(0) + + console.log('props', props) + + const init = useCallback(($container: null) => { + imgContainerRef.current = $container; + setIsReady(true); + }, []); + // ============================= viewer ========================= + const imgInsRef = useRef(null); + const [isImgReady, setIsImgReady] = useState(false); + + useEffect(() => { + console.log('123', 123) + if (!isReady || !imgContainerRef?.current) return; + const handleReady = addEventListenerWrapper(imgContainerRef.current, EVENT_VIEWER_READY, () => { + setIsImgReady(true); + }); + const handleTransformChange = addEventListenerWrapper( + imgContainerRef.current, + EVENT_VIEWER_TRANSFORM_CHANGE, + () => { + } + ); + imgInsRef.current = new Viewer(imgContainerRef.current, { + ...viewOption, + fitScaleAsMinScale: true, + image: generateImg(dataSource[currentIndex]?.imageKey), + }); + return () => { + handleReady?.remove(); + handleTransformChange?.remove(); + imgInsRef?.current?.destroy?.(); + imgInsRef.current = null; + }; + }, [isReady, currentIndex]); + + // ============================= viewer操作按钮 ========================= + const handleOptClick = (v: string) => { + switch (v) { + case 'zoomOut': + imgInsRef?.current?.scaleTo?.(0.1); + break; + case 'zoomIn': + imgInsRef?.current?.scaleTo?.(-0.1); + break; + case 'reset': + imgInsRef?.current?.reset?.(-0.1); + break; + } + }; + + // ============================= cropper ========================= + // 手动截图相关参数 + const cropInsRef: any = useRef(null); + const [showCrop, setShowCrop] = useState(showOpt); + const [cropType, setCropType] = useState(CROP_TYPE['AUTO']); + + // 自动截图相关参数 + const [odList, setOdList] = useState([]); + const [extendOdList, setExtendOdList] = useState([]); + const [selectRectId, setSelectRectId] = useState(null); + + // 定位按钮相关参数 + const alginContainerRef: any = useRef(null); + const alignRef: any = useRef(null); + const [cropRect, setCropRect] = useState(null); + + // 选中的版本号 + const [selectAlgorithmVersion, setSelectAlgorithmVersion] = useState(null); + const handlerCropStartRef: any = useRef(null); + const handlerCropEndRef: any = useRef(null); + const handleShapeSelectRef: any = useRef(null); + + useEffect(() => { + initData(dataSource[currentIndex].objects || objects) + return () => { + imgInsRef.current?.clearShape?.(); + handlerCropStartRef.current?.remove(); + handlerCropEndRef.current?.remove(); + handleShapeSelectRef.current?.remove(); + cropInsRef?.current?.destroy?.(); + cropInsRef.current = null; + }; + }, [isImgReady, showCrop, cropType, currentIndex]); + + const initData = (_objects: IOdRectOrigin[]) => { + const imgIns = imgInsRef.current; + const _odRect = dataSource[currentIndex].odRect + //清理crop + setCropRect(null); + if (!isImgReady) return; + if (!showCrop) { + imgIns?.addShape?.({ + x: get(_odRect, 'x', 0), + y: get(_odRect, 'y', 0), + w: get(_odRect, 'w', 0), + h: get(_odRect, 'h', 0), + selectAble: false, + }); + return; + } + + // 自动模式 + if (cropType === CROP_TYPE['AUTO']) { + const handleGetOD = (odList: any) => { + const imgSize = imgIns.getImgSize(); + const shapeList = odList.map((rect: { [x: string]: any; algorithmVersion: any; }) => ({ + ...rect, + selectAble: true, + id: rect['id'], + algorithmVersion: rect.algorithmVersion, + })); + imgIns.replaceShape(shapeList); + //顺便吧扩展框拿到 + const extendRect = shapeList.map((rect: { algorithmVersion: string; }) => { + // @ts-ignore + const _extendRect = getExtendRect(rect, imgSize.w, imgSize.h, rect.algorithmVersion); + return { ...rect, ..._extendRect }; + }); + setExtendOdList(extendRect); + imgIns.replaceShape(shapeList); + handleShapeSelectRef.current = addEventListenerWrapper(imgContainerRef.current, 'shape-select', (e: { detail: any; }) => { + const id = e.detail; + setSelectRectId(id); + const selectShape = shapeList.find((v: { [x: string]: any; }) => v['id'] === id); + if (selectShape) { + setSelectAlgorithmVersion(selectShape['algorithmVersion']); + //换算成屏幕坐标 + const axisRect = imgIns.imgRectAxisToCanvasAxisRect(selectShape); + const rect = { + x: axisRect.x2 > axisRect.x ? axisRect.x : axisRect.x2, + y: axisRect.y2 > axisRect.y ? axisRect.y : axisRect.y2, + w: Math.abs(axisRect.x2 - axisRect.x), + h: Math.abs(axisRect.y2 - axisRect.y), + }; + setCropRect(rect); + } else { + // @ts-ignore + setCropRect(null); + } + }); + }; + // @ts-ignore + const rect = getOdRect({ objects: _objects }) + setOdList(rect); + handleGetOD(rect); + } + + // 手动模式 + if (cropType === CROP_TYPE['CUSTOM']) { + // 手动框选状态预先清除imgIns + imgIns?.clearShape?.(); + handlerCropStartRef.current = addEventListenerWrapper(imgContainerRef.current, EVENT_CROP_START, () => { + setSelectAlgorithmVersion(null); + setCropRect(null); + }); + handlerCropEndRef.current = addEventListenerWrapper(imgContainerRef.current, EVENT_CROP_END, (event: { detail: any; }) => { + const data = event.detail; + setSelectAlgorithmVersion(null); + setCropRect({ + x: data.left, + y: data.top, + w: data.width, + h: data.height, + }); + alignRef?.current?.forceAlign?.(); + }); + cropInsRef.current = new Cropper(imgContainerRef.current, { + showMask: true, + viewer: imgIns, + }); + } + } + + // 获取框选的截图框信息 + const latestCropType = useLatest(cropType); + const latestImgKey = useLatest(dataSource[currentIndex].imageKey); + const latestCropRect = useLatest(cropRect); + const getCropInfo = async () => { + const cropType = latestCropType.current; + const cropRect = latestCropRect.current; + const imgIns = imgInsRef.current; + const transform = imgIns.targetTransform; + let newImgKey = latestImgKey.current; + let rectList: any = []; + let extendRectList = []; + let selectIndex = 0; + switch (cropType) { + case CROP_TYPE['AUTO']: + const shapes = imgIns.getSelectShape(); + const shapeIds = shapes.map((v: { [x: string]: any; }) => v['id']); + rectList = odList + .filter((v: { [x: string]: any; }) => shapeIds.includes(v['id'])) + .map((item: any) => { + if ( + item.algorithmVersion === 'OBJECT_TYPE_FACE' || + item.objectType === 'OBJECT_TYPE_FACE' + ) { + if (!isNull(item.extendBox)) { + return { + ...item, + w: get(item, 'extendBox.w'), + h: get(item, 'extendBox.h'), + x: get(item, 'extendBox.x'), + y: get(item, 'extendBox.y'), + }; + } + } else { + return item; + } + }); + extendRectList = extendOdList + .filter((v) => shapeIds.includes(v['id'])) + .map((v) => pick(v, ['x', 'y', 'w', 'h', 'algorithmVersion', 'id'])); + selectIndex = rectList.findIndex((v: { [x: string]: null; }) => v['id'] === selectRectId); + break; + default: + //获取旋转过的坐标 + // @ts-ignore + const newRect = getTransformRect(imgIns.image, transform, cropRect); + //判断是不是旋转过 + if (get(transform, 'rotate', 0) % 360 != 0) { + const data = getRotateImg(imgIns.image, get(transform, 'rotate', 0)) as any; + //在画布上画旋转后的图片 + newImgKey = await upload(data) as any; + } + rectList.push(newRect); + extendRectList.push(newRect); + break; + } + //扩展框获取imgkey + await Promise.all( + extendRectList.map(async (rect, index) => { + const file = await getFileByRect(imgIns.image, rect); + const imgKey = await upload(file); + extendRectList[index] = { ...rect, imgKey }; + }) + ); + //人脸图获取矫正图 + await Promise.all( + rectList.map(async (rect: { [x: string]: any; }, index: string | number) => { + const faceCorrectImage = rect['faceCorrectImage']; + let faceCorrectImageKey; + if (faceCorrectImage) { + const base64 = `data:image/jpg;base64,${faceCorrectImage}`; + const blobData = dataURLToBlob(base64); + const file = new window.File([blobData], `${new Date().getTime()}`); + faceCorrectImageKey = await upload(file); + } + const newRect: any = { + ...rect, + ...(faceCorrectImageKey ? { faceCorrectImageKey } : {}), + }; + delete newRect['faceCorrectImage']; + rectList[index] = newRect; + }) + ); + return { rectList, extendRectList, selectIndex, imgKey: newImgKey }; + }; + + // 操作界面判断 + const handleCropBtnClick = (v: string) => { + switch (v) { + case 'close': + setShowCrop(false); + break; + case 'autoCrop': + setCropType(CROP_TYPE['AUTO']); + break; + case 'customCrop': + setCropType(CROP_TYPE['CUSTOM']); + break; + } + }; + + // ============================= attact img ========================= + const [selectAttachImgIndex, setSelectAttachImgIndex] = useState(0); + const [isZoomin, setIsZoomin] = useState(false); + + /** + * 修改当前图片预览下标 + * @param diff 跳转强度 正向后翻、负值向前翻 + */ + const handleChangeIndex = (diff: number) => { + const _index = currentIndex + diff + + if (!dataSource?.[_index]?.imageKey) return + setCurrentIndex(_index) + } + + // ============================== Ref =============================== + useImperativeHandle(ref, () => ({ + imgInsRef, + setShowCrop, + initData, + getCropInfo, + handleChangeIndex + })); + + return ( +
    + {/*场景图大图 */} + {dataSource.length ? + <> +
    + {/* 图片操作 */} + {!hideLeftTopBtn && ( + + )} + {showCrop && ( + + )} + {showCrop && cropRect && screenshotButtonRender && ( + <> +
    + + {screenshotButtonRender({ + model: 'IMAGE', + getCropInfo, + setShowCrop, + cropType, + selectAlgorithmVersion, + })} + + + )} + {/* 场景图小图 */} + {dataSource[currentIndex].attachImg?.length && !showCrop && ( +
    +
    + {showAttachImgLabel + ? dataSource[currentIndex].attachImg?.map(({ label }, index) => ( +
    { + setSelectAttachImgIndex(index); + }} + > + {label} +
    + )) + : null} +
    +
    + +
    + +
    + )} + {showScore &&
    + {`人脸质量分:${(Number(dataSource[currentIndex].score) as number).toFixed(2)}`} +
    } + + : + + } +
    + ); +}); + +BigImagePreview.displayName = 'BigImagePreview'; + +export default BigImagePreview; diff --git a/packages/meta/src/BigImagePreview/bigImagePreviewHelper.ts b/packages/meta/src/BigImagePreview/bigImagePreviewHelper.ts new file mode 100644 index 0000000..e69de29 diff --git a/packages/meta/src/BigImagePreview/components/ScreenhotButtons/index.tsx b/packages/meta/src/BigImagePreview/components/ScreenhotButtons/index.tsx index 8ce3fdb..c50a562 100644 --- a/packages/meta/src/BigImagePreview/components/ScreenhotButtons/index.tsx +++ b/packages/meta/src/BigImagePreview/components/ScreenhotButtons/index.tsx @@ -11,7 +11,7 @@ interface IScreenShotButton { getCropInfo: () => void setShowCrop: any cropType: string - selectAlgorithmVersion: AlgorithmVersion + selectAlgorithmVersion?: AlgorithmVersion | null } const getScreenshotButtonRender = (arg: { @@ -75,9 +75,9 @@ const getScreenshotButtonRender = (arg: { selectAlgorithmVersion !== 0 && ( + diff --git a/packages/meta/src/BigImagePreview/index.tsx b/packages/meta/src/BigImagePreview/index.tsx index 36dc99f..b24e175 100644 --- a/packages/meta/src/BigImagePreview/index.tsx +++ b/packages/meta/src/BigImagePreview/index.tsx @@ -1,540 +1,5 @@ -import React, { useEffect, ReactElement, useState, useCallback, useRef, useImperativeHandle } from 'react'; -import classNames from 'classnames'; -import { useLatest } from '@zhst/hooks'; -import { - get, - pick, - isNull, - generateImg, - dataURLToBlob, - getOdRect, - getExtendRect, - getTransformRect, - getRotateImg, - getTransforms, - addEventListenerWrapper, - upload, - getFileByRect -} from '@zhst/func'; -import Align from 'rc-align'; -import { Button } from 'antd'; -import type { Rect, IScreenshotButtonProp, ODRECT, AlignType, ViewOption, IOdRectOrigin } from '@zhst/types' -import Icon from '../iconfont'; -import { - Cropper, - Viewer, - EVENT_VIEWER_TRANSFORM_CHANGE, - EVENT_VIEWER_READY, - EVENT_CROP_START, - EVENT_CROP_END, -} from '../ImageEditor'; -import BtnGroup from './components/BtnGroup'; -import './index.less' -import getScreenshotButtonRender from './components/ScreenhotButtons'; +import BigImagePreview from './BigImagePreview' -const componentName = `zhst-image__img-view`; +export type { ImgViewProps } from './BigImagePreview' -export const CROP_TYPE = { - CUSTOM: 'CSUTOM', - AUTO: 'AUTO', -}; - -export const defaultAlignOption = { - points: ['bl', 'br'], - offset: [6, 0], - overflow: { - adjustX: true, - adjustY: true, - }, -}; - -export interface ImgViewProps extends React.HTMLAttributes { - imageKey: string; //不在监听url变化 更新走销毁 - odRect: ODRECT; - attachImg?: Array<{ label: string; url: string }>; // 缩略图列表 - showAttachImgLabel: boolean; // 是否显示缩略图 - showOpt: boolean; // 是否显示操作面板 - width?: string | number; - height?: string | number; - /* 截图渲染 */ - screenshotButtonAlign: AlignType; - screenshotButtonRender: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; - hideLeftTopBtn?: boolean; - score?: number; - viewOption?: ViewOption; - objects: IOdRectOrigin[] -} -export interface ImgViewRef { - /* 图片实例 */ - imgInsRef: React.MutableRefObject; - /* 切换编辑模式 */ - setShowCrop: React.Dispatch>; -} - -const cropBtnDataSource = [ - { - key: 'close', - icon: 'icon-danchuangguanbi', - title: '退出', - }, - { - key: 'autoCrop', - icon: 'icon-zidong', - title: '智能框选', - }, - { - key: 'customCrop', - icon: 'icon-shoudong', - title: '手动框选', - }, -]; - -const operateBtnDataSource = [ - { - key: 'zoomOut', - icon: 'icon-fangda', - title: '放大', - }, - { - key: 'zoomIn', - icon: 'icon-suoxiao', - title: '缩小', - }, - { - key: 'reset', - icon: 'icon-zhongzhi3', - title: '重置图片', - }, -]; - -export const ImgView = React.forwardRef((props, ref) => { - const { - imageKey, - width, - height, - odRect, - score = 0, - attachImg = [], - objects = [], - showOpt = false, - showAttachImgLabel = true, - screenshotButtonAlign = defaultAlignOption, - screenshotButtonRender = getScreenshotButtonRender({ - onBigImageActionClick: () => {}, - disableBtn: [], - }), - hideLeftTopBtn = true, - viewOption = {} - } = props; - const imgContainerRef = React.useRef(null); - const [isReady, setIsReady] = useState(false); - - console.log('props', props) - - const init = useCallback(($container: null) => { - imgContainerRef.current = $container; - setIsReady(true); - }, []); - // ============================= viewer ========================= - const imgInsRef = useRef(null); - const [isImgReady, setIsImgReady] = useState(false); - - useEffect(() => { - if (!isReady) return; - const handleReady = addEventListenerWrapper(imgContainerRef.current, EVENT_VIEWER_READY, () => { - setIsImgReady(true); - }); - const handleTransformChange = addEventListenerWrapper( - imgContainerRef.current, - EVENT_VIEWER_TRANSFORM_CHANGE, - () => { - } - ); - imgInsRef.current = new Viewer(imgContainerRef.current, { - ...viewOption, - fitScaleAsMinScale: true, - image: generateImg(imageKey), - }); - return () => { - handleReady?.remove(); - handleTransformChange?.remove(); - imgInsRef?.current?.destroy?.(); - imgInsRef.current = null; - }; - }, [isReady, imageKey]); - - // ============================= viewer操作按钮 ========================= - const handleOptClick = (v: string) => { - switch (v) { - case 'zoomOut': - imgInsRef?.current?.scaleTo?.(0.1); - break; - case 'zoomIn': - imgInsRef?.current?.scaleTo?.(-0.1); - break; - case 'reset': - imgInsRef?.current?.reset?.(-0.1); - break; - } - }; - - // ============================= cropper ========================= - // 手动截图相关参数 - const cropInsRef = useRef(null); - const [showCrop, setShowCrop] = useState(showOpt); - const [cropType, setCropType] = useState(CROP_TYPE['AUTO']); - - // 自动截图相关参数 - const [odList, setOdList] = useState([]); - const [extendOdList, setExtendOdList] = useState([]); - const [selectRectId, setSelectRectId] = useState(null); - - // 定位按钮相关参数 - const aliginContainerRef = useRef(null); - const alignRef = useRef(null); - const [cropRect, setCropRect] = useState(null); - - // 选中的版本号 - const [selectAlgorithmVersion, setSelectAlgorithmVersion] = useState(null); - const handlerCropStartRef = useRef(null); - const handlerCropEndRef = useRef(null); - const handleShapeSelectRef = useRef(null); - - useEffect(() => { - initData(objects) - return () => { - imgInsRef.current?.clearShape?.(); - handlerCropStartRef.current?.remove(); - handlerCropEndRef.current?.remove(); - handleShapeSelectRef.current?.remove(); - cropInsRef?.current?.destroy?.(); - cropInsRef.current = null; - }; - }, [isImgReady, showCrop, cropType]); - - const initData = (_objects: IOdRectOrigin[]) => { - const imgIns = imgInsRef.current; - //清理crop - setCropRect(null); - if (!isImgReady) return; - if (!showCrop) { - imgIns?.addShape?.({ - x: get(odRect, 'x', 0), - y: get(odRect, 'y', 0), - w: get(odRect, 'w', 0), - h: get(odRect, 'h', 0), - selectAble: false, - }); - return; - } - if (cropType === CROP_TYPE['AUTO']) { - const handleGetOD = (odList: any) => { - const imgSize = imgIns.getImgSize(); - const shapeList = odList.map((rect: { [x: string]: any; algorithmVersion: any; }) => ({ - ...rect, - selectAble: true, - id: rect['id'], - algorithmVersion: rect.algorithmVersion, - })); - imgIns.replaceShape(shapeList); - //顺便吧扩展框拿到 - const extendRect = shapeList.map((rect: { algorithmVersion: string; }) => { - const extendRect = getExtendRect(rect, imgSize.w, imgSize.h, rect.algorithmVersion); - return { ...rect, ...extendRect }; - }); - setExtendOdList(extendRect); - imgIns.replaceShape(shapeList); - handleShapeSelectRef.current = addEventListenerWrapper(imgContainerRef.current, 'shape-select', (e) => { - const id = e.detail; - setSelectRectId(id); - const selectShape = shapeList.find((v) => v['id'] === id); - if (selectShape) { - setSelectAlgorithmVersion(selectShape['algorithmVersion']); - //换算成屏幕坐标 - const axisRect = imgIns.imgRectAxisToCanvasAxisRect(selectShape); - const rect = { - x: axisRect.x2 > axisRect.x ? axisRect.x : axisRect.x2, - y: axisRect.y2 > axisRect.y ? axisRect.y : axisRect.y2, - w: Math.abs(axisRect.x2 - axisRect.x), - h: Math.abs(axisRect.y2 - axisRect.y), - }; - setCropRect(rect); - } else { - // @ts-ignore - setCropRect(null); - } - }); - }; - const rect = getOdRect({ objects }) - setOdList(rect); - handleGetOD(rect); - } - - if (cropType === CROP_TYPE['CUSTOM']) { - // 手动框选状态预先清除imgIns - imgIns?.clearShape?.(); - handlerCropStartRef.current = addEventListenerWrapper(imgContainerRef.current, EVENT_CROP_START, (event) => { - setSelectAlgorithmVersion(null); - setCropRect(null); - }); - handlerCropEndRef.current = addEventListenerWrapper(imgContainerRef.current, EVENT_CROP_END, (event) => { - const data = event.detail; - setSelectAlgorithmVersion(null); - setCropRect({ - x: data.left, - y: data.top, - w: data.width, - h: data.height, - }); - alignRef?.current?.forceAlign?.(); - }); - cropInsRef.current = new Cropper(imgContainerRef.current, { - showMask: true, - viewer: imgIns, - }); - } - } - - // 获取框选的截图框信息 - const latestCropType = useLatest(cropType); - const latestImgKey = useLatest(imageKey); - const latestCropRect = useLatest(cropRect); - const getCropInfo = async () => { - const cropType = latestCropType.current; - const cropRect = latestCropRect.current; - const imgIns = imgInsRef.current; - const transform = imgIns.targetTransform; - let newImgKey = latestImgKey.current; - let rectList = []; - let extendRectList = []; - let selectIndex = 0; - switch (cropType) { - case CROP_TYPE['AUTO']: - const shapes = imgIns.getSelectShape(); - const shapeIds = shapes.map((v) => v['id']); - rectList = odList - .filter((v) => shapeIds.includes(v['id'])) - .map((item: any) => { - if ( - item.algorithmVersion === 'OBJECT_TYPE_FACE' || - item.objectType === 'OBJECT_TYPE_FACE' - ) { - if (!isNull(item.extendBox)) { - return { - ...item, - w: get(item, 'extendBox.w'), - h: get(item, 'extendBox.h'), - x: get(item, 'extendBox.x'), - y: get(item, 'extendBox.y'), - }; - } - } else { - return item; - } - }); - extendRectList = extendOdList - .filter((v) => shapeIds.includes(v['id'])) - .map((v) => pick(v, ['x', 'y', 'w', 'h', 'algorithmVersion', 'id'])); - selectIndex = rectList.findIndex((v) => v['id'] === selectRectId); - break; - default: - //获取旋转过的坐标 - const newRect = getTransformRect(imgIns.image, transform, cropRect); - //判断是不是旋转过 - if (get(transform, 'rotate', 0) % 360 != 0) { - const data = getRotateImg(imgIns.image, get(transform, 'rotate', 0)); - //在画布上画旋转后的图片 - newImgKey = await upload(data); - } - rectList.push(newRect); - extendRectList.push(newRect); - break; - } - //扩展框获取imgkey - await Promise.all( - extendRectList.map(async (rect, index) => { - const file = await getFileByRect(imgIns.image, rect); - const imgKey = await upload(file); - extendRectList[index] = { ...rect, imgKey }; - }) - ); - //人脸图获取矫正图 - await Promise.all( - rectList.map(async (rect, index) => { - const faceCorrectImage = rect['faceCorrectImage']; - let faceCorrectImageKey; - if (faceCorrectImage) { - const base64 = `data:image/jpg;base64,${faceCorrectImage}`; - const blobData = dataURLToBlob(base64); - const file = new window.File([blobData], `${new Date().getTime()}`); - faceCorrectImageKey = await upload(file); - } - const newRect = { - ...rect, - ...(faceCorrectImageKey ? { faceCorrectImageKey } : {}), - }; - delete newRect['faceCorrectImage']; - rectList[index] = newRect; - }) - ); - return { rectList, extendRectList, selectIndex, imgKey: newImgKey }; - }; - - // 操作界面判断 - const handleCropBtnClick = (v: string) => { - switch (v) { - case 'close': - setShowCrop(false); - break; - case 'autoCrop': - setCropType(CROP_TYPE['AUTO']); - break; - case 'customCrop': - setCropType(CROP_TYPE['CUSTOM']); - break; - } - }; - - // ============================= attact img ========================= - const showAttachImg = attachImg.length !== 0; - const [selectAttachImgIndex, setSelectAttachImgIndex] = useState(0); - const [isZoomin, setIsZoomin] = useState(false); - - // ============================== Ref =============================== - useImperativeHandle(ref, () => ({ - imgInsRef, - setShowCrop, - initData, - })); - - return ( -
    - {/*场景图大图 */} -
    - {/* 图片操作 */} - {!hideLeftTopBtn && ( - - )} - {showCrop && ( - - )} - {showCrop && cropRect && screenshotButtonRender && ( - <> -
    - - {screenshotButtonRender({ - model: 'IMAGE', - getCropInfo, - setShowCrop, - cropType, - selectAlgorithmVersion, - })} - - - )} - {/* 场景图小图 */} - {showAttachImg && !showCrop && ( -
    -
    - {showAttachImgLabel - ? attachImg.map(({ label, url }, index) => ( -
    { - setSelectAttachImgIndex(index); - }} - > - {label} -
    - )) - : null} -
    -
    - -
    - -
    - )} -
    {`人脸质量分:${(score as number).toFixed(2)}`}
    -
    - ); -}); - -ImgView.displayName = 'ImgView'; - -export default ImgView; +export default BigImagePreview diff --git a/packages/meta/src/ImagePreview/index.tsx b/packages/meta/src/CompareImage/CompareImage.tsx similarity index 80% rename from packages/meta/src/ImagePreview/index.tsx rename to packages/meta/src/CompareImage/CompareImage.tsx index 03e8d5c..8ad3926 100644 --- a/packages/meta/src/ImagePreview/index.tsx +++ b/packages/meta/src/CompareImage/CompareImage.tsx @@ -1,4 +1,4 @@ -import React, { useRef, useState, FC, useEffect, useCallback } from 'react' +import React, { useRef, useState, FC, useEffect, forwardRef, useImperativeHandle } from 'react' import { generateImg, get, addEventListenerWrapper } from '@zhst/func'; import { useUpdateEffect } from '@zhst/hooks'; import { Button } from 'antd'; @@ -10,39 +10,36 @@ import './index.less' const componentName = `zhst-image__compater-view`; -export interface CompaterImageProps { +export interface CompareImageProps { /** * @description 属性描述 * @default "默认值" */ - url: string; label: string; openRoll?: boolean; //开启滚动模式 - urls?: Array; - specialTitle: String; - noTargetImageTip?: string; - score?: number; + dataSource?: Array<{ + url: string; + score: number; + }>; + showScore?: boolean; // 是否展示相似度 + current: number; // 当前图片下标 } + +export interface CompareImageRefProps { + +} + // 对比图组件 -const CompaterImage: FC = (props) => { - const { url, label, openRoll = false, urls = [], score } = props; +const CompareImage = forwardRef((props, ref) => { + const { label, openRoll = false, dataSource = [], showScore = true, current = 0 } = props; const imgContainerRef = useRef(null); const imgInsRef = useRef(null); const [scale, setScale] = useState(0); //图片翻页机制 - const [showUrl, setShowUrl] = useState(generateImg(url)); //记录显示的图片 - - useUpdateEffect(() => { - setShowUrl(generateImg(url)); - if (imgInsRef.current) { - imgInsRef.current?.refleshImage({ - image: generateImg(url), - }); - } - }, [url]); + const [currentIndex, setCurrentIndex] = useState(current) + // 初始化页面 useEffect(() => { - setShowUrl(url); const handleTransformChange = addEventListenerWrapper( imgContainerRef.current, 'viewer-transform-change', @@ -52,9 +49,11 @@ const CompaterImage: FC = (props) => { } ); - imgInsRef.current = new Viewer(imgContainerRef.current, { - image: generateImg(url), - }); + if (generateImg(dataSource[currentIndex].url)) { + imgInsRef.current = new Viewer(imgContainerRef.current, { + image: generateImg(dataSource[currentIndex].url), + }); + } return () => { handleTransformChange?.remove(); @@ -63,34 +62,36 @@ const CompaterImage: FC = (props) => { }; }, []); - //向前翻页 - const handlePre = useCallback(() => { - const index = urls.findIndex((v) => v === showUrl); - if (index > 0) { - const newUrl = urls[index - 1]; - setShowUrl(newUrl); + // 监听下标变化 + useUpdateEffect(() => { + if (imgInsRef.current) { imgInsRef.current?.refleshImage({ - image: newUrl, + image: generateImg(dataSource[currentIndex].url), }); } - }, [showUrl, urls]); - //向后翻页 - const handleNext = useCallback(() => { - const index = urls.findIndex((v) => v === showUrl); - if (index >= 0 && !!urls[index + 1]) { - const newUrl = urls[index + 1]; - setShowUrl(newUrl); - imgInsRef.current?.refleshImage({ - image: newUrl, - }); - } - }, [showUrl, urls]); + }, [currentIndex]); + + // 翻页实践 + const handleIndexChange = (changeVal: number) => { + const _index = currentIndex + changeVal + + if (!dataSource?.[_index]?.url) return + imgInsRef.current?.refleshImage({ + image: generateImg(dataSource[_index].url), + }); + setCurrentIndex(_index) + } + + useImperativeHandle(ref, () => ({ + imgInsRef, + handleIndexChange + })); return (
    {label}
    - {!url && ( + {!dataSource.length && (
    = (props) => { 暂无匹配数据
    )} - {score && } - {!!url && openRoll && ( + {/* 翻页组件 */} + {!!dataSource.length && openRoll && (
    {/*
    */}
    )} + {showScore && }
    ); -}; +}) -export default CompaterImage +export default CompareImage diff --git a/packages/meta/src/CompareImage/components/CornerScore/index.less b/packages/meta/src/CompareImage/components/CornerScore/index.less new file mode 100644 index 0000000..cb8bf35 --- /dev/null +++ b/packages/meta/src/CompareImage/components/CornerScore/index.less @@ -0,0 +1,21 @@ +.zhst-image__CornerScore { + position: absolute; + right: 0; + bottom: 0; + width: 56px; + height: 22px; + line-height: 22px; + text-align: right; + padding-right: 1px; + background-size: 100%; + background-image: url('data: image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAAAsCAYAAAC9rDzHAAAByUlEQVR4Xu2cO08DMRCEJy0tlNBCSwmU0EIJLbS0UEILLTX/Fo3kk1AUHrrsjB3dWIoUnZTdvfnOZ6+1mxXGGHsADgEcA9hvnyMAvJ7xiwKrjuoQ0HmDxu8ZMxToAZDQrgAE2gxg6z9xAjwFcAvgoCDumGgKuADeA7iI6vUKqAFyE/KU12U9uMmiGuBr4Ong0bIS4A2Aa234sa4CyFzuPfLqFVABfGg5nv4OFu5BAZAbl4+F62q7fQVAJul3tjtYuCMFwEcATNozDAooAL7ltMVATngS8+kLP54UMzAAjc9VABrFVrgKQIWqRpsBaBRb4SoAFaoabQagUWyFqwBUqGq0GYBGsRWuAlChqtFmABrFVrgKQIWqRpsBaBRb4SoAFaoabVYDZLU1K9EyTApUA2RzyrMp9rgRlBWylIIlFRkmBapnIIuZ0hJmgkc3lQBTzGQEN7mqApjNSwd4VTOQr8yXFDL1IbjtDOTMY/dR1r0+/LZaA1n7yb6/wOsEb+4rlMDYdZR0oSO4uZuYtEkPAO17CP9dA3nCwll3Mlj8iw/nL4ABN/gj8hPAgBsc3KY1kJuTs7Y5yV+B7BBA5nKXrSUsKcGOgJvC/ALSJBp5mBHCFAAAAABJRU5ErkJggg=='); + z-index: 99; + + &>span { + padding-right: 6px; + line-height: 22px; + font-size: 12px; + vertical-align: middle; + color: rgba(255, 255, 255, 100%); + } +} diff --git a/packages/meta/src/ImagePreview/components/CornerScore/index.tsx b/packages/meta/src/CompareImage/components/CornerScore/index.tsx similarity index 100% rename from packages/meta/src/ImagePreview/components/CornerScore/index.tsx rename to packages/meta/src/CompareImage/components/CornerScore/index.tsx diff --git a/packages/meta/src/CompareImage/images/emptyImage.png b/packages/meta/src/CompareImage/images/emptyImage.png new file mode 100644 index 0000000..9762957 Binary files /dev/null and b/packages/meta/src/CompareImage/images/emptyImage.png differ diff --git a/packages/meta/src/CompareImage/images/percent_background.png b/packages/meta/src/CompareImage/images/percent_background.png new file mode 100644 index 0000000..ebde317 Binary files /dev/null and b/packages/meta/src/CompareImage/images/percent_background.png differ diff --git a/packages/meta/src/CompareImage/index.less b/packages/meta/src/CompareImage/index.less new file mode 100644 index 0000000..378f365 --- /dev/null +++ b/packages/meta/src/CompareImage/index.less @@ -0,0 +1,147 @@ +.zhst-image__compater-view { + display: flex; + width: 100%; + align-items: center; + justify-content: center; + + &>div:first-child { + margin-right: 25px; + } + + &>div:last-child { + margin-left: 25px; + } + + &__container { + position: relative; + width: 345px; + height: 460px; + box-sizing: content-box; + border: 1px solid #f0f0f0; + } + + &__view { + width: 345px; + height: 460px; + } + + &__label { + position: absolute; + z-index: 99; + top: 0; + left: 0; + display: flex; + height: 34px; + align-items: center; + justify-content: center; + + // width: 48px; + padding: 0 6px; + background: #09f; + color: #fff; + } + + &__tool { + display: flex; + width: 345px; + height: 40px; + align-items: center; + justify-content: center; + background: #f9f9f9; + + i, + span { + color: #333 !important; + } + + i { + margin-right: 4px; + } + + &>*:not(:last-child) { + margin-right: 20px; + } + + &__scale { + display: inline-block; + width: 38px; + height: 16px; + + // margin-left: 15px; + box-sizing: content-box; + border: 1px solid rgb(77 77 77 / 100%); + background: rgb(255 255 255 / 100%); + border-radius: 2px; + color: #4d4d4d; + cursor: default; + font-size: 12px; + line-height: 16px; + text-align: center; + } + + &__line { + width: 1px; + height: 14px; + background: #e6e6e6; + } + } + + &__empty { + position: absolute; + z-index: 9; + display: flex; + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background: #f9f9f9; + transform: translateY(-100%); + + &>img { + width: 140px; + height: 80px; + } + + &--text { + color: #999; + font-size: 14px; + line-height: 22px; + } + } + + &__scoll-module { + position: absolute; + top: 0%; + left: 0%; + display: flex; + width: 100%; + height: 100%; + align-items: flex-end; + justify-content: space-between; + pointer-events: none; + + &__btn { + display: flex; + width: 50px; + height: 50px; + align-items: center; + justify-content: center; + margin: 6px; + border-radius: 50%; + opacity: 0.5; + pointer-events: all; + + &>span { + display: flex; + align-items: center; + justify-content: center; + } + } + + &__btn:hover { + background-color: #09f !important; + color: #fff !important; + } + } +} diff --git a/packages/meta/src/CompareImage/index.md b/packages/meta/src/CompareImage/index.md new file mode 100644 index 0000000..0e7b9e9 --- /dev/null +++ b/packages/meta/src/CompareImage/index.md @@ -0,0 +1,50 @@ +--- +nav: + title: 元组件 + order: 1 +group: + title: 通用 + order: 3 +--- + +# CompareImage 图片预览 + +```jsx +import React, { useRef } from 'react'; +import { CompareImage } from '@zhst/meta' +import { Button, Space } from 'antd' + +const props = { + label: "目标图", + openRoll:true, + dataSource:[ + { + url: 'http://10.0.0.120:30003/file/public/public_20240110/file/60f26318-19fc-40b3-b249-91bd2a4da3f3.jpg', + score: '0.5' + }, + { + url: 'http://10.0.0.120:30003/file/public/public_20240110/file/7c9b33a8-5106-4982-9d58-a593ad8acbf6.jpg', + score: '0.8' + }, + ] +} + +export default () => { + const ref = useRef(null) + + return ( + + + + + + ) +} +``` + +| 参数名 | 参数类型 | 参数说明 | +| ------ | -------- | ---- | +|label|string|左上角标题| +|openRoll|boolean|是否支持鼠标滚动放大缩小| +|urls|string[]|链接数组| +|score|string|相似度| diff --git a/packages/meta/src/CompareImage/index.tsx b/packages/meta/src/CompareImage/index.tsx new file mode 100644 index 0000000..56bc164 --- /dev/null +++ b/packages/meta/src/CompareImage/index.tsx @@ -0,0 +1,5 @@ +import CompareImage from "./CompareImage"; + +export type { CompareImageProps } from './CompareImage' + +export default CompareImage diff --git a/packages/meta/src/ImagePreview/index.md b/packages/meta/src/ImagePreview/index.md deleted file mode 100644 index c487093..0000000 --- a/packages/meta/src/ImagePreview/index.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -nav: - title: 元组件 - order: 1 -group: - title: 通用 - order: 3 ---- - -# ImagePreview 图片预览 - -```jsx -import React from 'react'; -import { ImagePreview } from '@zhst/meta' - -const props = { - label:"目标图", - url:"http://10.0.0.120:30003/file/public/public_20240110/file/60f26318-19fc-40b3-b249-91bd2a4da3f3.jpg", - openRoll:true, - score: 0.8, - urls:[ - "http://10.0.0.120:30003/file/public/public_20240110/file/60f26318-19fc-40b3-b249-91bd2a4da3f3.jpg", - "http://10.0.0.120:30003/file/public/public_20240110/file/7c9b33a8-5106-4982-9d58-a593ad8acbf6.jpg" - ] -} - -export default () => { - return ( - - ) -} -``` - -| 参数名 | 参数类型 | 参数说明 | -| ------ | -------- | ---- | -|label|string|左上角标题| -|url|string|链接| -|openRoll|boolean|是否支持鼠标滚动放大缩小| -|urls|string[]|链接数组| -|score|string|相似度| diff --git a/packages/meta/src/VideoPlayer/VideoPlayer.tsx b/packages/meta/src/VideoPlayer/VideoPlayer.tsx new file mode 100644 index 0000000..6571019 --- /dev/null +++ b/packages/meta/src/VideoPlayer/VideoPlayer.tsx @@ -0,0 +1,676 @@ +import React, { Dispatch, ReactElement, SetStateAction, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; +import { + noop, + get, + addEventListenerWrapper, + dataURLToBlob, + nextTick, + toRealNumber, + getTransforms, + formatDurationTime +} from '@zhst/func'; +import Align from 'rc-align'; +import { Rect, IScreenshotButtonProp, AlignType } from '@zhst/types' +import { useLatest, useUpdateEffect, useFullscreen, useUnmount } from '@zhst/hooks'; +import classNames from 'classnames'; +import download from 'downloadjs'; +import { Button, message } from 'antd'; +import Icon from '../iconfont'; +import { + Cropper, + EVENT_CROP_START, + EVENT_CROP_END, +} from '../ImageEditor'; +import FlvPlayer, { FLV_EVENT } from './components/FlvPlayer'; +import Range from './components/Progress'; +import Loading from './components/Loading'; +import getScreenshotButtonRender from '../BigImagePreview/components/ScreenhotButtons'; +import { CROP_TYPE } from '../utils/constants'; +import { getShowStatus } from './videoPlayerHelper' +import './index.less' + +const componentName = `zhst-image__video-view`; + +export interface VideoViewProps { + /* 播放地址 */ + url: string; + /* 播放总时间 */ + maxDuration?: number; + /* 截图渲染 */ + screenshotButtonAlign?: AlignType; + screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; + /* 默认截图框 */ + defautlNormalizationRect?: Rect; + /* 截图回调 */ + onCropChange?: (showCrop: boolean, normalizationRect: null | Rect) => void; +} + +export interface VideoViewRef { + /* 当前图片模式 */ + cropAble: boolean; + setShowCrop: Dispatch>; + downloadVideoframe: () => void; +} + +const VideoPlayer = forwardRef((props, ref) => { + const { + url, + maxDuration, + screenshotButtonAlign = { + points: ['bl', 'br'], + offset: [6, 0], + overflow: { + adjustX: true, + adjustY: true, + }, + }, + screenshotButtonRender = getScreenshotButtonRender({ + onBigImageActionClick: () => {}, + disableBtn: [], + }), + onCropChange, + defautlNormalizationRect: defaultNormalizationRect, + } = props; + const videoType = useMemo(() => (url && url.startsWith('http') ? 'mp4' : 'flv'), [url]); + // ========================== 播放 ========================= + //实例参数 + const containerRef: any = useRef(null); //容器ref + const videoRef: any = useRef(null); //video 标签dom + const videoInsRef: any = useRef(null); //flv 实例 + const [playSeq, setPlaySeq] = useState(0); // 通过重置playid使FLV组件重新渲染 + const videoRemoveListener = useRef(noop); //移除dom监听的中间函数 + const loadingTimeRef = useRef(0); //最后一次加载时间 + const delayLoadingTimer: any = useRef(null); //算loading的定时器 + //状态参数 + const [isReady, setIsReady] = useState(false); // + const [isPlay, setIsPlay] = useState(false); //当前是否播放 + + const [isEnd, setIsEnd] = useState(false); //是否播放结束 + const [isError, setIsError] = useState(false); //播放出错 + const [isVideoLoadFinished, setIsVideoLoadFinish] = useState(false); //是否缓存加载完成 + const [playTime, setPlayTime] = useState(0); //当前播放时间 + const [isLoadingVideo, setIsLoadingVideo] = useState(true); //是否加载中 + const [isDelayLoading, setIsDelayLoading] = useState(false); //显示的转圈loading 延迟0.2s显示 + //设置延迟转圈圈 + const latestIsLoadingVideo = useLatest(isLoadingVideo); + const setIsLoadingVideoWrapper = (isLoading: boolean) => { + setIsLoadingVideo((preLoading) => { + if (!preLoading && isLoading) { + loadingTimeRef.current = new Date().getTime(); + } + if (!isLoading) { + loadingTimeRef.current = null; + } + //延迟0。2s相关 + if (!isLoading) { + setIsDelayLoading(false); + } + if (!delayLoadingTimer.current && preLoading) { + delayLoadingTimer.current = setTimeout(() => { + if (latestIsLoadingVideo.current) { + //0.2s后才显示 + setIsDelayLoading(true); + } + delayLoadingTimer.current = null; + }, 200); + } + return isLoading; + }); + }; + // 初始化loading 30s 直接显示错误 + // TODO :逻辑忘记了 不应该是每次init player吗? + useEffect(() => { + let timer = setInterval(() => { + if (loadingTimeRef.current) { + if (new Date().getTime() - loadingTimeRef.current > 1000 * 30) { + checkIsErr() + } + } + }, 1000); + return () => { + clearInterval(timer); + }; + }, []); + + //结束的时候暂停 保证不播了 + useUpdateEffect(() => { + if (isEnd) { + videoInsRef?.current?.pause?.(); + } + }, [isEnd]); + + // 捕捉视频播放报错 + const checkIsErr = () => { + setIsError(true) + try { + videoInsRef?.current?.destroy?.(); + } catch (error) { + console.error(error); + } + } + + // 初始化 + const latestMaxDuration = useLatest(maxDuration); + const initPlayer = useCallback((ins: any, dom: any) => { + videoRef.current = dom; + videoInsRef.current = ins; + const maxDuration = latestMaxDuration.current || 0; + //监听播放事件 + let video = dom; + let errorLister = (e: any) => { + checkIsErr(); + console.error('视频出错了', e, video.currentTime); + }; + let waitingListener = (e: any) => { + setIsLoadingVideoWrapper(true); + console.debug('视频加载等待', e, video.currentTime); + }; + let playingListener = (e: any) => { + setIsLoadingVideoWrapper(false); + setIsError(false) + console.debug('视频从等待中播放', e, video.currentTime); + }; + let playLister = (e: any) => { + setIsPlay(true); + setIsError(false) + console.debug('提示该视频正在播放中', e, video.currentTime); + }; + let pauseListener = (e: any) => { + setIsPlay(false); + console.debug('暂停播放', e, video.currentTime); + }; + let endedListner = (e: any) => { + setIsEnd(true); + setIsVideoLoadFinish(true); + console.debug('视频播放完了', e, video.currentTime); + }; + let timeupdateListner = (e: any) => { + console.debug( + '视频播放时间更新', + e, + video.currentTime, + videoRef.current?.duration, + maxDuration + ); + let nowTime = video.currentTime; + if (nowTime >= maxDuration) { + setIsEnd(true); + setIsVideoLoadFinish(true); + } + setPlayTime(nowTime); + }; + // see https://github.com/bilibili/flv.js/issues/337 + let windowErrorHandle = (errorEvent: any) => { + try { + if ( + errorEvent['message'] == + "Uncaught TypeError: Cannot read property 'flushStashedSamples' of null" + ) { + checkIsErr(); + console.error('视频出错了 window监听', errorEvent); + } + } catch (error) { + console.error(error); + } + }; + video.addEventListener('error', errorLister); + video.addEventListener('waiting', waitingListener); + video.addEventListener('playing', playingListener); + video.addEventListener('play', playLister); + video.addEventListener('pause', pauseListener); + video.addEventListener('ended', endedListner); + video.addEventListener('timeupdate', timeupdateListner); + window.addEventListener('error', windowErrorHandle); + + videoRemoveListener.current = () => { + video.removeEventListener('error', errorLister); + video.removeEventListener('waiting', waitingListener); + video.removeEventListener('playing', playingListener); + video.removeEventListener('play', playLister); + video.removeEventListener('pause', pauseListener); + video.removeEventListener('ended', endedListner); + video.removeEventListener('timeupdate', timeupdateListner); + window.removeEventListener('error', windowErrorHandle); + }; + + videoInsRef?.current.on(FLV_EVENT.ERROR, (type: any, errDetail: any, info: any) => { + checkIsErr(); + console.error('videoInsRef 错误', type, errDetail, info, video.currentTime); + }); + let playPromise = videoInsRef?.current.play(); + //先ready 遮挡会导致播放失败 + setIsReady(true); + playPromise + .then(() => { + setIsReady(true); + }) + .catch((...arg: any) => { + try { + } catch (error) {} + // setIsError(true); + console.error('playPromise视频出错了', arg); + }); + }, []); + + useUnmount(() => { + try { + videoRemoveListener.current(); + } catch (e) { + console.error(e); + } + }); + + const reload = async () => { + if (videoInsRef.current) { + let oldTime = videoInsRef.current.currentTime; + videoInsRef.current.currentTime = 0; + + //如果修改时间不成功,则走重新加载的逻辑 + if (oldTime === videoInsRef.current.currentTime) { + //重置状态 + setIsReady(false); + setIsPlay(false); + setIsLoadingVideoWrapper(false); + setIsReady(false); + setIsEnd(false); + setIsVideoLoadFinish(false); + setPlayTime(0); + + //清楚dom事件监听 + try { + videoRemoveListener.current(); + } catch (error) { + console.error(error); + } + setPlaySeq((pre) => pre + 1); + return; + } + videoInsRef.current.play(); + } + + setPlayTime(0); + setIsEnd(false); + }; + const seek = (v: number) => { + if (videoInsRef.current && isVideoLoadFinished) { + setPlayTime(parseFloat(v as any)); + videoInsRef.current.currentTime = parseFloat(v as any); + } else { + message.warning('待视频加载完,才可操作进度条') + } + }; + // ========================== 视频opt bar ========================= + const [isFullscreen, { toggleFullscreen }] = useFullscreen(containerRef, { + pageFullscreen: true, + }); + const showMaxDuration = !!maxDuration + ? maxDuration + : toRealNumber(get(videoRef, 'current.duration', 0)); + const showSlider = videoInsRef.current && isVideoLoadFinished; + const showStatus: any = getShowStatus(isDelayLoading, isEnd, isError); + + // ========================== 截图 ========================= + const corpContainerRef: any = useRef(); + const cropInsRef: any = useRef(null); + const [showCrop, setShowCrop] = useState(false); + + //回显默认框选 + const isFirstFlagRef = useRef(true); + useEffect(() => { + const isFirst = isFirstFlagRef.current; + if (!isLoadingVideo && isReady && isFirst && defaultNormalizationRect && !showStatus) { + nextTick(() => { + setShowCrop(true); + }); + } + }, [isLoadingVideo, showStatus]); + + //定位按钮相关参数 + const alginContainerRef: any = useRef(null); + const alignRef: any = useRef(null); + const [cropRect, setCropRect] = useState(null); + + useEffect(() => { + showCrop ? videoInsRef?.current?.pause() : videoInsRef?.current?.play(); + }, [showCrop]); + + useEffect(() => { + let handlerCropStart: { remove: () => void; }; + let handlerCropEnd: { remove: () => void; }; + setCropRect(null); + if (!isReady) return; + if (showCrop) { + handlerCropStart = addEventListenerWrapper(corpContainerRef.current, EVENT_CROP_START, () => { + setCropRect(null); + }); + handlerCropEnd = addEventListenerWrapper(corpContainerRef.current, EVENT_CROP_END, (event: { detail: any; }) => { + const data = event.detail; + setCropRect({ + x: data.left, + y: data.top, + w: data.width, + h: data.height, + }); + alignRef?.current?.forceAlign?.(); + }); + let video: any = videoRef.current; + //计算 limitcroppbox + let scale = Math.min( + video.offsetWidth / video.videoWidth, + video.offsetHeight / video.videoHeight + ); + let finalVideoWidth = video.videoWidth * scale; + let finalVideoHeight = video.videoHeight * scale; + let cropBoxLimited = { + width: finalVideoWidth, + height: finalVideoHeight, + top: (video.offsetHeight - finalVideoHeight) / 2, + left: (video.offsetWidth - finalVideoWidth) / 2, + }; + //获取视频图片 + let canvas = document.createElement('canvas'); + canvas.width = video.offsetWidth; + canvas.height = video.offsetHeight; + canvas.style.display = 'none'; + document.body.appendChild(canvas); + let ctx = canvas.getContext('2d'); + ctx?.drawImage( + video, + (video.offsetWidth - finalVideoWidth) / 2, + (video.offsetHeight - finalVideoHeight) / 2, + finalVideoWidth, + finalVideoHeight + ); + let imageData = canvas.toDataURL('image/png'); + canvas.parentNode?.removeChild(canvas); + //回显编辑框 + const isFirst = isFirstFlagRef.current; + let initialCropBoxData = null; + if (isFirst && defaultNormalizationRect) { + initialCropBoxData = { + left: defaultNormalizationRect.x * finalVideoWidth + cropBoxLimited.left, + top: defaultNormalizationRect.y * finalVideoHeight + cropBoxLimited.top, + width: defaultNormalizationRect.w * finalVideoWidth, + height: defaultNormalizationRect.h * finalVideoHeight, + }; + } + isFirstFlagRef.current = false; + + cropInsRef.current = new Cropper(corpContainerRef.current, { + showMask: true, + cropBoxLimited, + img: imageData, + initialCropBoxData, + }); + } + return () => { + handlerCropStart?.remove(); + handlerCropEnd?.remove(); + cropInsRef?.current?.destroy?.(); + cropInsRef.current = null; + }; + }, [showCrop, isReady]); + + const latestCropRect = useLatest(cropRect); + + const getCropInfo = async () => { + const cropRect = latestCropRect.current as any; + let video: any = videoRef.current; + if (!video) return + let rectList = []; + let extendRectList = []; + let selectIndex = 0; + //获取视频图片的url + let scale = Math.min( + video.offsetWidth / video.videoWidth, + video.offsetHeight / video.videoHeight + ); + let finalVideoWidth = video.videoWidth * scale; + let finalVideoHeight = video.videoHeight * scale; + let canvas = document.createElement('canvas'); + canvas.width = finalVideoWidth; + canvas.height = finalVideoHeight; + canvas.style.display = 'none'; + document.body.appendChild(canvas); + let ctx = canvas.getContext('2d') as CanvasRenderingContext2D; + ctx.drawImage( + video, + 0, + 0, + finalVideoWidth, + finalVideoHeight + ); + let base64 = canvas.toDataURL('image/jpeg'); + const blobData = dataURLToBlob(base64); + canvas.parentNode?.removeChild(canvas); + const file = new window.File([blobData], `${new Date().getTime()}`); + let newRect = { + w: cropRect.w / finalVideoWidth, + h: cropRect.h / finalVideoHeight, + x: (cropRect.x - (video.offsetWidth - finalVideoWidth) / 2) / finalVideoWidth, + y: (cropRect.y - (video.offsetHeight - finalVideoHeight) / 2) / finalVideoHeight + }; + rectList.push(newRect); + extendRectList.push(newRect); + //扩展框获取imgkey + extendRectList.forEach(async (rect, index) => { + extendRectList[index] = { + ...rect, + }; + }) + return { + rectList, + extendRectList, + selectIndex, + file + }; + }; + + //回调 + useEffect(() => { + //计算归一化crop rect + let normalizationRect = null; + if (showCrop && cropRect) { + let video: any = videoRef.current; + let scale = Math.min( + video.offsetWidth / video.videoWidth, + video.offsetHeight / video.videoHeight + ); + let finalVideoWidth = video.videoWidth * scale; + let finalVideoHeight = video.videoHeight * scale; + let cropBoxLimited = { + width: finalVideoWidth, + height: finalVideoHeight, + top: (video.offsetHeight - finalVideoHeight) / 2, + left: (video.offsetWidth - finalVideoWidth) / 2, + }; + normalizationRect = { + x: (cropRect.x - cropBoxLimited.left) / cropBoxLimited.width, + y: (cropRect.y - cropBoxLimited.top) / cropBoxLimited.height, + w: cropRect.w / cropBoxLimited.width, + h: cropRect.h / cropBoxLimited.height, + }; + } + + onCropChange?.(showCrop, normalizationRect); + }, [showCrop, cropRect]); + + // ========================== 截帧 ========================= + const downloadVideoframe = useCallback(async () => { + try { + videoInsRef?.current?.pause?.(); + let video: any = videoRef.current; + var canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d') + let base64; + //当视频处于还未加载出来时,截屏为黑色图片 + if (video.readyState === 0) { + ctx?.clearRect(0, 0, canvas.width, canvas.height); + canvas.width = video.offsetWidth; + canvas.height = video.offsetHeight; + // @ts-ignore + ctx.fillStyle = 'black'; + ctx?.fillRect(0, 0, canvas.width, canvas.height); + base64 = canvas.toDataURL(); + } else { + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + ctx?.drawImage(video, 0, 0, canvas.width, canvas.height); + base64 = canvas.toDataURL('image/png'); + } + download(base64); + } catch (error) { + console.error(error); + } + }, []); + + // ============================== 暴露出去的方法 =============================== + const latestIsReady = useLatest(isReady); + const cropAble = !showStatus && isReady; + useImperativeHandle(ref, () => ({ + cropAble, + setShowCrop: (dispatch) => { + const isReady = latestIsReady.current; + if (!isReady) return; + setShowCrop(dispatch); + }, + downloadVideoframe, + })); + + return ( +
    + {url && ( + <> + + {/* //截图 */} +
    + {/*
    */} +
    + {showCrop && cropRect && screenshotButtonRender && ( + <> +
    + + {screenshotButtonRender({ + model: 'IMAGE', + getCropInfo, + setShowCrop, + cropType: CROP_TYPE['CUSTOM'], + })} + + + )} + {/* 视频进度条 */} + {!showCrop && ( +
    +
    + +
    +
    { + e.stopPropagation(); + }} + > + +
    + {/* TODO: 删除扩展方法format */} + {formatDurationTime(playTime)}/{formatDurationTime(showMaxDuration)} +
    +
    +
    + +
    +
    + )} + {/* mask */} + {!!showStatus && ( + reload()} /> + )} + + )} +
    + ); +}); + +export default VideoPlayer; diff --git a/packages/meta/src/VideoPlayer/components/FlvPlayer/index.tsx b/packages/meta/src/VideoPlayer/components/FlvPlayer/index.tsx index edc23e5..b34b981 100644 --- a/packages/meta/src/VideoPlayer/components/FlvPlayer/index.tsx +++ b/packages/meta/src/VideoPlayer/components/FlvPlayer/index.tsx @@ -33,7 +33,7 @@ export default class VideoPlayer extends Component { curPlayUrl: '', shouldReinit: false, }; - flvPlayer = null; + flvPlayer: any = null; videoElement = null; static getDerivedStateFromProps = (nextProps: { url?: any; playId?: any; }, prevState: { curPlayUrl?: any; playId?: any; }) => { @@ -59,20 +59,40 @@ export default class VideoPlayer extends Component { if ($video) { - if (flvjs.isSupported() && this.props.url && this.props.url !== '') { + if (flvjs.isSupported() && this.props.url && this.props.url) { const reload = () => { if (this.flvPlayer && this.flvPlayer.destroy) { try { - this.flvPlayer?.destroy(); + this.flvPlayer.destroy() } catch (error) { console.error(error); } } - let flvPlayer = flvjs.createPlayer({ ...others }, config); + let flvPlayer = flvjs.createPlayer({ ...others }, { + deferLoadAfterSourceOpen: false, + ...config + }); flvPlayer.attachMediaElement($video); flvPlayer.load(); this.flvPlayer = flvPlayer; + // @ts-ignore + let controller = this.flvPlayer._transmuxer._controller + let wsLoader = controller._ioctl._loader + const oldWsOnCompleteFunc = wsLoader._onComplete + wsLoader._onComplete = function() { + if(!controller._remuxer) { + controller._remuxer = { + destroy: () => { + console.log('组件销毁') + }, + flushStashedSamples: () => { + console.log("flushStashedSamples") + } + } + } + oldWsOnCompleteFunc() + } this.flvPlayer.reload = reload; onCreat && onCreat(this.flvPlayer, $video); }; diff --git a/packages/meta/src/VideoPlayer/components/Loading/index.tsx b/packages/meta/src/VideoPlayer/components/Loading/index.tsx index b6cc17e..0da447c 100644 --- a/packages/meta/src/VideoPlayer/components/Loading/index.tsx +++ b/packages/meta/src/VideoPlayer/components/Loading/index.tsx @@ -7,7 +7,7 @@ import './index.less' const componentName = `zhst-image__video-view`; export interface ILoading { - status: 'LOADING' | 'COMPLETED' | 'END' | 'ERROR' + status: 'LOADING' | 'COMPLETED' | 'END' | 'ERROR' | null reload: () => void } diff --git a/packages/meta/src/VideoPlayer/components/Progress/index.tsx b/packages/meta/src/VideoPlayer/components/Progress/index.tsx index 1d3b821..9aea069 100644 --- a/packages/meta/src/VideoPlayer/components/Progress/index.tsx +++ b/packages/meta/src/VideoPlayer/components/Progress/index.tsx @@ -1,12 +1,15 @@ import React from 'react'; import classNames from 'classnames'; import { Slider } from 'antd'; +import type { SliderSingleProps } from 'antd' import './index.less'; const componentName = `zhst-image__range`; -export interface RangeWrapperProps extends React.HTMLAttributes { +export interface RangeWrapperProps extends SliderSingleProps { showSlider: boolean; + className?: string; + min: number; } export const Range: React.FC = (props) => { diff --git a/packages/meta/src/VideoPlayer/index.md b/packages/meta/src/VideoPlayer/index.md index e1abe8d..f879582 100644 --- a/packages/meta/src/VideoPlayer/index.md +++ b/packages/meta/src/VideoPlayer/index.md @@ -9,19 +9,31 @@ group: # VideoPlayer 视频播放 +:::warning{title=注意} +播放进度条操作还未完善,在播放结束和拖拽的过程中都有一定程度卡顿,目前逻辑待优化 +::: + ```jsx -import React from 'react'; +import React, { useRef, useState } from 'react'; +import { Space, Button } from 'antd' import { VideoPlayer } from '@zhst/meta' -const props = { - "flvUrl":"ws://10.0.0.120:9033/flv/HaikangNvr/45.flv?ip=10.0.2.103&stime=1705051970&etime=1705051990", - "maxDuration":20, - "showCrop$":false -} - export default () => { + const videoRef = useRef(null) + const [url, setUrl] = useState('ws://10.0.0.120:9033/flv/Sip/34020000001310000301.flv?ip=10.0.0.120&stime=1704815972&etime=1704815992') + return ( - + + + + + + ) } ``` + +| 参数名 | 参数类型 | 参数说明 | +| ------ | -------- | ---- | +| url | string(必填) | 当前视频链接 | +| maxDuration | number(必填) | 视频截取长度 | diff --git a/packages/meta/src/VideoPlayer/index.tsx b/packages/meta/src/VideoPlayer/index.tsx index 46e5703..57e073e 100644 --- a/packages/meta/src/VideoPlayer/index.tsx +++ b/packages/meta/src/VideoPlayer/index.tsx @@ -1,696 +1,5 @@ -import React, { Dispatch, ReactElement, SetStateAction, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; -import { - noop, - get, - addEventListenerWrapper, - dataURLToBlob, - nextTick, - toRealNumber, - getTransforms, - formatDurationTime -} from '@zhst/func'; -import Align from 'rc-align'; -import { Rect, IScreenshotButtonProp, AlignType } from '@zhst/types' -import { useLatest, useUpdateEffect, useFullscreen, useUnmount } from '@zhst/hooks'; -import classNames from 'classnames'; -import download from 'downloadjs'; -import { Button, message } from 'antd'; -import Icon from '../iconfont'; -import { - Cropper, - EVENT_CROP_START, - EVENT_CROP_END, -} from '../ImageEditor'; -import FlvPlayer, { FLV_EVENT } from './components/FlvPlayer'; -import Range from './components/Progress'; -import Loading, { ILoading } from './components/Loading'; -import getScreenshotButtonRender from '../BigImagePreview/components/ScreenhotButtons'; -import './index.less' +import VideoPlayer from './VideoPlayer' -const componentName = `zhst-image__video-view`; +export type { VideoViewProps, VideoViewRef } from './VideoPlayer' -export const CROP_TYPE = { - CUSTOM: 'CSUTOM', - AUTO: 'AUTO', -}; - -export function getShowStatus(isLoadingVideo: boolean, isEnd: boolean, isError: boolean): ILoading['status'] { - let status = null; - if (isLoadingVideo) { - status = 'LOADING'; - } - if (isError) { - status = 'ERROR'; - } - if (isEnd) { - status = 'END'; - } - return status; -} - - -export interface VideoViewProps { - /* 播放地址 */ - flvUrl: string; - /* 播放总时间 */ - maxDuration?: number; - /* 截图渲染 */ - screenshotButtonAlign?: AlignType; - screenshotButtonRender?: (screenshotButtonProp: IScreenshotButtonProp) => ReactElement; - /* 默认截图框 */ - defautlNormalizationRect?: Rect; - /* 截图回调 */ - onCropChange?: (showCrop: boolean, normalizationRect: null | Rect) => void; -} - -export interface VideoViewRef { - /* 当前图片模式 */ - cropAble: boolean; - setShowCrop: Dispatch>; - downloadVideoframe: () => void; -} - -const VideoPlayer = forwardRef((props, ref) => { - const { - flvUrl, - maxDuration, - screenshotButtonAlign = { - points: ['bl', 'br'], - offset: [6, 0], - overflow: { - adjustX: true, - adjustY: true, - }, - }, - screenshotButtonRender = getScreenshotButtonRender({ - onBigImageActionClick: () => {}, - disableBtn: [], - }), - onCropChange, - defautlNormalizationRect: defaultNormalizationRect, - } = props; - const videoType = useMemo(() => (flvUrl && flvUrl.startsWith('http') ? 'mp4' : 'flv'), [flvUrl]); - // ========================== 播放 ========================= - //实例参数 - const containerRef = useRef(null); //容器ref - const videoRef = useRef(null); //video 标签dom - const videoInsRef: any = useRef(null); //flv 实例 - const [playSeq, setPlaySeq] = useState(0); // 通过重置playid使FLV组件重新渲染 - const videoRemoveListener = useRef(noop); //移除dom监听的中间函数 - const loadingTimeRef = useRef(0); //最后一次加载时间 - const delayLoadingTimer = useRef(null); //算loading的定时器 - //状态参数 - const [isReady, setIsReady] = useState(false); // - const [isPlay, setIsPlay] = useState(false); //当前是否播放 - - const [isEnd, setIsEnd] = useState(false); //是否播放结束 - const [isError, setIsError] = useState(false); //播放出错 - const [isVideoLoadFinished, setIsVideoLoadFinish] = useState(false); //是否缓存加载完成 - const [playTime, setPlayTime] = useState(0); //当前播放时间 - const [isLoadingVideo, setIsLoadingVideo] = useState(true); //是否加载中 - const [isDelayLoading, setIsDelayLoading] = useState(false); //显示的转圈loading 延迟0.2s显示 - //设置延迟转圈圈 - const latestIsLoadingVideo = useLatest(isLoadingVideo); - const setIsLoadingVideoWrapper = (isLoading: boolean) => { - setIsLoadingVideo((preLoading) => { - if (!preLoading && isLoading) { - loadingTimeRef.current = new Date().getTime(); - } - if (!isLoading) { - loadingTimeRef.current = null; - } - //延迟0。2s相关 - if (!isLoading) { - setIsDelayLoading(false); - } - if (!delayLoadingTimer.current && preLoading) { - delayLoadingTimer.current = setTimeout(() => { - if (latestIsLoadingVideo.current) { - //0.2s后才显示 - setIsDelayLoading(true); - } - delayLoadingTimer.current = null; - }, 200); - } - return isLoading; - }); - }; - // 初始化loading 30s 直接显示错误 - // TODO :逻辑忘记了 不应该是每次init player吗? - useEffect(() => { - let timer = setInterval(() => { - if (loadingTimeRef.current) { - if (new Date().getTime() - loadingTimeRef.current > 1000 * 30) { - checkIsErr() - } - } - }, 1000); - return () => { - clearInterval(timer); - }; - }, []); - - //结束的时候暂停 保证不播了 - useUpdateEffect(() => { - if (isEnd) { - videoInsRef?.current?.pause?.(); - } - }, [isEnd]); - - // 捕捉视频播放报错 - const checkIsErr = () => { - setIsError(true) - try { - videoInsRef?.current?.destroy?.(); - } catch (error) { - console.error(error); - } - } - - // 初始化 - const latestMaxDuration = useLatest(maxDuration); - const initPlayer = useCallback((ins: any, dom: any) => { - videoRef.current = dom; - videoInsRef.current = ins; - const maxDuration = latestMaxDuration.current || 0; - //监听播放事件 - let video = dom; - let errorLister = (e: any) => { - checkIsErr(); - console.error('视频出错了', e, video.currentTime); - }; - let waitingListener = (e: any) => { - setIsLoadingVideoWrapper(true); - console.debug('视频加载等待', e, video.currentTime); - }; - let playingListener = (e: any) => { - setIsLoadingVideoWrapper(false); - setIsError(false) - console.debug('视频从等待中播放', e, video.currentTime); - }; - let playLister = (e: any) => { - setIsPlay(true); - setIsError(false) - console.debug('提示该视频正在播放中', e, video.currentTime); - }; - let pauseListener = (e: any) => { - setIsPlay(false); - console.debug('暂停播放', e, video.currentTime); - }; - let endedListner = (e: any) => { - setIsEnd(true); - setIsVideoLoadFinish(true); - console.debug('视频播放完了', e, video.currentTime); - }; - let timeupdateListner = (e: any) => { - console.debug( - '视频播放时间更新', - e, - video.currentTime, - videoRef.current?.duration, - maxDuration - ); - let nowTime = video.currentTime; - if (nowTime >= maxDuration) { - setIsEnd(true); - setIsVideoLoadFinish(true); - } - setPlayTime(nowTime); - }; - // see https://github.com/bilibili/flv.js/issues/337 - let windowErrorHandle = (errorEvent: { [x: string]: string; }) => { - try { - if ( - errorEvent['message'] == - "Uncaught TypeError: Cannot read property 'flushStashedSamples' of null" - ) { - checkIsErr(); - console.error('视频出错了 window监听', errorEvent); - } - } catch (error) { - console.error(error); - } - }; - video.addEventListener('error', errorLister); - video.addEventListener('waiting', waitingListener); - video.addEventListener('playing', playingListener); - video.addEventListener('play', playLister); - video.addEventListener('pause', pauseListener); - video.addEventListener('ended', endedListner); - video.addEventListener('timeupdate', timeupdateListner); - window.addEventListener('error', windowErrorHandle); - - videoRemoveListener.current = () => { - video.removeEventListener('error', errorLister); - video.removeEventListener('waiting', waitingListener); - video.removeEventListener('playing', playingListener); - video.removeEventListener('play', playLister); - video.removeEventListener('pause', pauseListener); - video.removeEventListener('ended', endedListner); - video.removeEventListener('timeupdate', timeupdateListner); - window.removeEventListener('error', windowErrorHandle); - }; - - videoInsRef?.current.on(FLV_EVENT.ERROR, (type: any, errDetail: any, info: any) => { - checkIsErr(); - console.error('videoInsRef 错误', type, errDetail, info, video.currentTime); - }); - let playPromise = videoInsRef?.current.play(); - //先ready 遮挡会导致播放失败 - setIsReady(true); - playPromise - .then(() => { - setIsReady(true); - }) - .catch((...arg: any) => { - try { - } catch (error) {} - // setIsError(true); - console.error('playPromise视频出错了', arg); - }); - }, []); - - useUnmount(() => { - try { - videoRemoveListener.current(); - } catch (e) { - console.error(e); - } - }); - - const reload = async () => { - if (videoInsRef.current) { - let oldTime = videoInsRef.current.currentTime; - videoInsRef.current.currentTime = 0; - - //如果修改时间不成功,则走重新加载的逻辑 - if (oldTime === videoInsRef.current.currentTime) { - //重置状态 - setIsReady(false); - setIsPlay(false); - setIsLoadingVideoWrapper(false); - setIsReady(false); - setIsEnd(false); - setIsVideoLoadFinish(false); - setPlayTime(0); - - //清楚dom事件监听 - try { - videoRemoveListener.current(); - } catch (error) { - console.error(error); - } - setPlaySeq((pre) => pre + 1); - return; - } - videoInsRef.current.play(); - } - - setPlayTime(0); - setIsEnd(false); - }; - const seek = (v: string) => { - if (videoInsRef.current && isVideoLoadFinished) { - setPlayTime(parseFloat(v)); - videoInsRef.current.currentTime = parseFloat(v); - } else { - message.warning('待视频加载完,才可操作进度条') - } - }; - // ========================== 视频opt bar ========================= - const [isFullscreen, { toggleFullscreen }] = useFullscreen(containerRef, { - pageFullscreen: true, - }); - const showMaxDuration = !!maxDuration - ? maxDuration - : toRealNumber(get(videoRef, 'current.duration', 0)); - const showSlider = videoInsRef.current && isVideoLoadFinished; - const showStatus = getShowStatus(isDelayLoading, isEnd, isError); - - // ========================== 截图 ========================= - const corpContainerRef = useRef(); - const cropInsRef = useRef(null); - const [showCrop, setShowCrop] = useState(false); - - //回显默认框选 - const isFirstFlagRef = useRef(true); - useEffect(() => { - const isFirst = isFirstFlagRef.current; - if (!isLoadingVideo && isReady && isFirst && defaultNormalizationRect && !showStatus) { - nextTick(() => { - setShowCrop(true); - }); - } - }, [isLoadingVideo, showStatus]); - - //定位按钮相关参数 - const alginContainerRef = useRef(null); - const alignRef = useRef(null); - const [cropRect, setCropRect] = useState(null); - - useEffect(() => { - showCrop ? videoInsRef?.current?.pause() : videoInsRef?.current?.play(); - }, [showCrop]); - - useEffect(() => { - let handlerCropStart: { remove: () => void; }; - let handlerCropEnd: { remove: () => void; }; - setCropRect(null); - if (!isReady) return; - if (showCrop) { - handlerCropStart = addEventListenerWrapper(corpContainerRef.current, EVENT_CROP_START, (event) => { - setCropRect(null); - }); - handlerCropEnd = addEventListenerWrapper(corpContainerRef.current, EVENT_CROP_END, (event) => { - const data = event.detail; - setCropRect({ - x: data.left, - y: data.top, - w: data.width, - h: data.height, - }); - alignRef?.current?.forceAlign?.(); - }); - let video: any = videoRef.current; - //计算limitcroppbox - let scale = Math.min( - video.offsetWidth / video.videoWidth, - video.offsetHeight / video.videoHeight - ); - let finalVideoWidth = video.videoWidth * scale; - let finalVideoHeight = video.videoHeight * scale; - let cropBoxLimited = { - width: finalVideoWidth, - height: finalVideoHeight, - top: (video.offsetHeight - finalVideoHeight) / 2, - left: (video.offsetWidth - finalVideoWidth) / 2, - }; - //获取视频图片 - let canvas = document.createElement('canvas'); - canvas.width = video.offsetWidth; - canvas.height = video.offsetHeight; - canvas.style.display = 'none'; - document.body.appendChild(canvas); - let ctx = canvas.getContext('2d'); - ctx.drawImage( - video, - (video.offsetWidth - finalVideoWidth) / 2, - (video.offsetHeight - finalVideoHeight) / 2, - finalVideoWidth, - finalVideoHeight - ); - let imageData = canvas.toDataURL('image/png'); - canvas.parentNode?.removeChild(canvas); - //回显编辑框 - const isFirst = isFirstFlagRef.current; - let initialCropBoxData = null; - if (isFirst && defaultNormalizationRect) { - initialCropBoxData = { - left: defaultNormalizationRect.x * finalVideoWidth + cropBoxLimited.left, - top: defaultNormalizationRect.y * finalVideoHeight + cropBoxLimited.top, - width: defaultNormalizationRect.w * finalVideoWidth, - height: defaultNormalizationRect.h * finalVideoHeight, - }; - } - isFirstFlagRef.current = false; - - cropInsRef.current = new Cropper(corpContainerRef.current, { - showMask: true, - cropBoxLimited, - img: imageData, - initialCropBoxData, - }); - } - return () => { - handlerCropStart?.remove(); - handlerCropEnd?.remove(); - cropInsRef?.current?.destroy?.(); - cropInsRef.current = null; - }; - }, [showCrop, isReady]); - - const latestCropRect = useLatest(cropRect); - - const getCropInfo = async () => { - const cropRect = latestCropRect.current as any; - let video: any = videoRef.current; - if (!video) return - let rectList = []; - let extendRectList = []; - let selectIndex = 0; - //获取视频图片的url - let scale = Math.min( - video.offsetWidth / video.videoWidth, - video.offsetHeight / video.videoHeight - ); - let finalVideoWidth = video.videoWidth * scale; - let finalVideoHeight = video.videoHeight * scale; - let canvas = document.createElement('canvas'); - canvas.width = finalVideoWidth; - canvas.height = finalVideoHeight; - canvas.style.display = 'none'; - document.body.appendChild(canvas); - let ctx = canvas.getContext('2d') as CanvasRenderingContext2D; - ctx.drawImage( - video, - 0, - 0, - finalVideoWidth, - finalVideoHeight - ); - let base64 = canvas.toDataURL('image/jpeg'); - const blobData = dataURLToBlob(base64); - canvas.parentNode?.removeChild(canvas); - const file = new window.File([blobData], `${new Date().getTime()}`); - let newRect = { - w: cropRect.w / finalVideoWidth, - h: cropRect.h / finalVideoHeight, - x: (cropRect.x - (video.offsetWidth - finalVideoWidth) / 2) / finalVideoWidth, - y: (cropRect.y - (video.offsetHeight - finalVideoHeight) / 2) / finalVideoHeight - }; - rectList.push(newRect); - extendRectList.push(newRect); - //扩展框获取imgkey - extendRectList.forEach(async (rect, index) => { - extendRectList[index] = { - ...rect, - }; - }) - return { - rectList, - extendRectList, - selectIndex, - file - }; - }; - - //回调 - useEffect(() => { - //计算归一化crop rect - let normalizationRect = null; - if (showCrop && cropRect) { - let video: any = videoRef.current; - let scale = Math.min( - video.offsetWidth / video.videoWidth, - video.offsetHeight / video.videoHeight - ); - let finalVideoWidth = video.videoWidth * scale; - let finalVideoHeight = video.videoHeight * scale; - let cropBoxLimited = { - width: finalVideoWidth, - height: finalVideoHeight, - top: (video.offsetHeight - finalVideoHeight) / 2, - left: (video.offsetWidth - finalVideoWidth) / 2, - }; - normalizationRect = { - x: (cropRect.x - cropBoxLimited.left) / cropBoxLimited.width, - y: (cropRect.y - cropBoxLimited.top) / cropBoxLimited.height, - w: cropRect.w / cropBoxLimited.width, - h: cropRect.h / cropBoxLimited.height, - }; - } - - onCropChange?.(showCrop, normalizationRect); - }, [showCrop, cropRect]); - - // ========================== 截帧 ========================= - const downloadVideoframe = useCallback(async () => { - try { - videoInsRef?.current?.pause?.(); - let video: any = videoRef.current; - var canvas = document.createElement('canvas'); - const ctx = canvas.getContext('2d') - let base64; - //当视频处于还未加载出来时,截屏为黑色图片 - if (video.readyState === 0) { - ctx?.clearRect(0, 0, canvas.width, canvas.height); - canvas.width = video.offsetWidth; - canvas.height = video.offsetHeight; - // @ts-ignore - ctx.fillStyle = 'black'; - ctx?.fillRect(0, 0, canvas.width, canvas.height); - base64 = canvas.toDataURL(); - } else { - canvas.width = video.videoWidth; - canvas.height = video.videoHeight; - ctx?.drawImage(video, 0, 0, canvas.width, canvas.height); - base64 = canvas.toDataURL('image/png'); - } - download(base64); - } catch (error) { - console.error(error); - } - }, []); - - // ============================== 暴露出去的方法 =============================== - const latestIsReady = useLatest(isReady); - const cropAble = !showStatus && isReady; - useImperativeHandle(ref, () => ({ - cropAble, - setShowCrop: (dispatch) => { - const isReady = latestIsReady.current; - if (!isReady) return; - setShowCrop(dispatch); - }, - downloadVideoframe, - })); - - return ( -
    - {flvUrl && ( - <> - - {/* //截图 */} -
    - {/*
    */} -
    - {showCrop && cropRect && screenshotButtonRender && ( - <> -
    - - {screenshotButtonRender({ - model: 'IMAGE', - getCropInfo, - setShowCrop, - cropType: CROP_TYPE['CUSTOM'], - })} - - - )} - {/* 视频进度条 */} - {!showCrop && ( -
    -
    - -
    -
    { - e.stopPropagation(); - }} - > - -
    - {/* TODO: 删除扩展方法format */} - {formatDurationTime(playTime)}/{formatDurationTime(showMaxDuration)} -
    -
    -
    - -
    -
    - )} - {/* mask */} - {!!showStatus && ( - reload()} /> - )} - - )} -
    - ); -}); - -export default VideoPlayer; +export default VideoPlayer diff --git a/packages/meta/src/VideoPlayer/videoPlayerHelper.ts b/packages/meta/src/VideoPlayer/videoPlayerHelper.ts new file mode 100644 index 0000000..0ce9bf0 --- /dev/null +++ b/packages/meta/src/VideoPlayer/videoPlayerHelper.ts @@ -0,0 +1,14 @@ + +export function getShowStatus(isLoadingVideo: boolean, isEnd: boolean, isError: boolean) { + let status = null; + if (isLoadingVideo) { + status = 'LOADING'; + } + if (isError) { + status = 'ERROR'; + } + if (isEnd) { + status = 'END'; + } + return status; +} diff --git a/packages/meta/src/index.md b/packages/meta/src/index.md index b5316e0..c54cdfa 100644 --- a/packages/meta/src/index.md +++ b/packages/meta/src/index.md @@ -5,4 +5,61 @@ title: 快速上手 order: 1 --- +## 目录结构 + + +
      +
    • + src + 开发文件夹 +
        +
      • + Component1 + 组件目录 +
          +
        • + index.ts + 入口文件 +
        • +
        • + Component1.tsx + 组件1 +
        • +
        • + Component1Helper.ts + 组件函数 +
        • +
        • + index.less + 样式文件 +
        • +
        • + index.md + 说明文档 +
        • +
        +
      • +
      • + utils + 公共函数文件夹 +
      • +
      • + index.ts + 总入口文件 +
      • +
      +
    • +
    • + .dumirc.ts + 文档配置 +
    • +
    • + package.json + 这是 package.json +
    • +
    +
    + + + diff --git a/packages/meta/src/index.tsx b/packages/meta/src/index.tsx index 6d39fad..5582665 100644 --- a/packages/meta/src/index.tsx +++ b/packages/meta/src/index.tsx @@ -1,5 +1,5 @@ export { default as doubleClick } from './doubleClick'; export { default as Icon } from './iconfont'; -export { default as ImagePreview } from './ImagePreview' +export { default as CompareImage } from './CompareImage' export { default as BigImagePreview } from './BigImagePreview' export { default as VideoPlayer } from './VideoPlayer' diff --git a/packages/meta/src/utils/constants.ts b/packages/meta/src/utils/constants.ts new file mode 100644 index 0000000..3e90a79 --- /dev/null +++ b/packages/meta/src/utils/constants.ts @@ -0,0 +1,13 @@ +export const CROP_TYPE = { + CUSTOM: 'CSUTOM', + AUTO: 'AUTO', +}; + +export const defaultAlignOption = { + points: ['bl', 'br'], + offset: [6, 0], + overflow: { + adjustX: true, + adjustY: true, + }, +}; diff --git a/packages/request/CHANGELOG.md b/packages/request/CHANGELOG.md index 8ac9057..e1947d9 100644 --- a/packages/request/CHANGELOG.md +++ b/packages/request/CHANGELOG.md @@ -1,5 +1,11 @@ # @zhst/request +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + ## 0.2.4 ### Patch Changes diff --git a/packages/request/es/index.d.ts b/packages/request/es/index.d.ts new file mode 100644 index 0000000..746e3db --- /dev/null +++ b/packages/request/es/index.d.ts @@ -0,0 +1,32 @@ +import type { RequestOptionsInit } from 'umi-request'; +export declare class ResponseError extends Error { + name: string; + data: D; + response: Response; + request: { + url: string; + options: RequestOptionsInit; + }; + type: string; + constructor(response: Response, text: string, data: D, request: { + url: string; + options: RequestOptionsInit; + }, type?: string); +} +export declare const req: import("umi-request").RequestMethod; +export interface OPTION extends RequestOptionsInit { + toast?: boolean; +} +interface CGI { + method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; + url: string; + baseUrl?: string; + data?: { + [key: string]: any; + }; + useBaseUrl?: boolean; + originUrl?: boolean; + refererSuffix?: string; +} +export declare const doRequest: (cgi: CGI, option?: OPTION) => Promise; +export default doRequest; diff --git a/packages/request/es/index.js b/packages/request/es/index.js index e15cf6d..b0ed186 100644 --- a/packages/request/es/index.js +++ b/packages/request/es/index.js @@ -81,19 +81,25 @@ req.use( /*#__PURE__*/function () { return _context.abrupt("return"); case 14: isEmptyRes = d === ''; //有些后端接口成功会返回空 做下兼容 + if (res) { + _context.next = 17; + break; + } + return _context.abrupt("return"); + case 17: body = !isEmptyRes ? JSON.parse(d) : d; if (!(res.status >= 200 && res.status < 300)) { - _context.next = 20; + _context.next = 22; break; } ctx.res = body; - _context.next = 24; + _context.next = 26; break; - case 20: + case 22: // 先判断Grpc-Metadata-Errorx-Message errMsg = res.headers.get('Grpc-Metadata-Errorx-Message'); if (errMsg) { - errMsg = window.utf8.decode(base64.decode(errMsg)); + errMsg = base64.decode(errMsg); // 后判断 body中的message } else if (!errMsg && get(body, 'message')) { errMsg = "".concat(get(body, 'message')); @@ -103,21 +109,21 @@ req.use( /*#__PURE__*/function () { } toast && message.error(errMsg); throw new ResponseError(res, errMsg, d, req, 'CustomError'); - case 24: - _context.next = 30; - break; case 26: - _context.prev = 26; + _context.next = 32; + break; + case 28: + _context.prev = 28; _context.t0 = _context["catch"](2); if (get(_context.t0, 'type') !== 'CustomError') { toast && message.error('您的网络发生异常,无法连接服务器'); } throw _context.t0; - case 30: + case 32: case "end": return _context.stop(); } - }, _callee, null, [[2, 26]]); + }, _callee, null, [[2, 28]]); })); return function (_x, _x2) { return _ref.apply(this, arguments); @@ -172,7 +178,7 @@ export var doRequest = function doRequest(cgi, option) { } : { data: newData }; - return request(newUrl, _objectSpread(_objectSpread(_objectSpread({ + return req(newUrl, _objectSpread(_objectSpread(_objectSpread({ method: method }, paramObj), option), {}, { headers: _objectSpread({ diff --git a/packages/request/lib/index.d.ts b/packages/request/lib/index.d.ts new file mode 100644 index 0000000..746e3db --- /dev/null +++ b/packages/request/lib/index.d.ts @@ -0,0 +1,32 @@ +import type { RequestOptionsInit } from 'umi-request'; +export declare class ResponseError extends Error { + name: string; + data: D; + response: Response; + request: { + url: string; + options: RequestOptionsInit; + }; + type: string; + constructor(response: Response, text: string, data: D, request: { + url: string; + options: RequestOptionsInit; + }, type?: string); +} +export declare const req: import("umi-request").RequestMethod; +export interface OPTION extends RequestOptionsInit { + toast?: boolean; +} +interface CGI { + method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; + url: string; + baseUrl?: string; + data?: { + [key: string]: any; + }; + useBaseUrl?: boolean; + originUrl?: boolean; + refererSuffix?: string; +} +export declare const doRequest: (cgi: CGI, option?: OPTION) => Promise; +export default doRequest; diff --git a/packages/request/lib/index.js b/packages/request/lib/index.js new file mode 100644 index 0000000..9935c48 --- /dev/null +++ b/packages/request/lib/index.js @@ -0,0 +1,150 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + ResponseError: () => ResponseError, + default: () => src_default, + doRequest: () => doRequest, + req: () => req +}); +module.exports = __toCommonJS(src_exports); +var import_umi_request = require("umi-request"); +var import_lodash_es = require("lodash-es"); +var import_antd = require("antd"); +var import_user = require("@zhst/types/user"); +var import_base_64 = __toESM(require("base-64")); +var ResponseError = class extends Error { + constructor(response, text, data, request, type = "ResponseError") { + super(text || response.statusText); + this.name = "ResponseError"; + this.data = data; + this.response = response; + this.request = request; + this.type = type; + } +}; +var req = (0, import_umi_request.extend)({ + getResponse: true, + // timeout: 1000, + parseResponse: false +}); +req.use(async (ctx, next) => { + const { req: req2 } = ctx; + const { toast = true } = (req2 == null ? void 0 : req2.options) || {}; + try { + await next(); + const { res } = ctx; + const d = await res.text(); + if (res.status === 401) { + localStorage.removeItem(import_user.User.TOKEN_KEY); + localStorage.removeItem(import_user.User.USER_KEY); + import_antd.message.warning("登录过期,请重新登录!"); + return; + } + const isEmptyRes = d === ""; + if (!res) + return; + const body = !isEmptyRes ? JSON.parse(d) : d; + if (res.status >= 200 && res.status < 300) { + ctx.res = body; + } else { + let errMsg = res.headers.get("Grpc-Metadata-Errorx-Message"); + if (errMsg) { + errMsg = import_base_64.default.decode(errMsg); + } else if (!errMsg && (0, import_lodash_es.get)(body, "message")) { + errMsg = `${(0, import_lodash_es.get)(body, "message")}`; + } else { + errMsg = "您的网络发生异常,无法连接服务器"; + } + toast && import_antd.message.error(errMsg); + throw new ResponseError(res, errMsg, d, req2, "CustomError"); + } + } catch (error) { + if ((0, import_lodash_es.get)(error, "type") !== "CustomError") { + toast && import_antd.message.error("您的网络发生异常,无法连接服务器"); + } + throw error; + } +}); +var doRequest = (cgi, option) => { + const { + method, + url, + baseUrl, + data = {}, + useBaseUrl = true, + originUrl = false, + refererSuffix = "" + } = cgi; + const token = localStorage.getItem(import_user.User.TOKEN_KEY); + const userInfo = localStorage.getItem(import_user.User.USER_KEY) ? JSON.parse(localStorage.getItem(import_user.User.USER_KEY)) : null; + let newUrl = ""; + if (useBaseUrl) { + newUrl = `${baseUrl}${url}`; + } else { + newUrl = `http://10.0.0.7:32223${url}`; + } + if (originUrl) { + newUrl = url; + } + const regex = /\/:(\w+)/g; + const params = []; + let matches; + while ((matches = regex.exec(newUrl)) != null) { + if (matches[1]) { + params.push(matches[1]); + } + } + params.forEach(function(name) { + let d = data == null ? void 0 : data[name]; + if (d == null) { + d = ""; + } + newUrl = newUrl.replace(`:${name}`, d); + }); + const newData = (0, import_lodash_es.omit)(data, params); + const paramObj = method.toLowerCase() === "get" ? { params: newData } : { data: newData }; + return req(newUrl, { + method, + ...paramObj, + ...option, + headers: { + authorization: token, + ...refererSuffix ? { zhst_referer: `${baseUrl}${refererSuffix}` } : {} + } + }); +}; +var src_default = doRequest; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ResponseError, + doRequest, + req +}); diff --git a/packages/request/package.json b/packages/request/package.json index 955c4d4..9f9b43b 100644 --- a/packages/request/package.json +++ b/packages/request/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/request", - "version": "0.2.4", + "version": "0.3.0", "description": "请求库", "keywords": [ "request", diff --git a/packages/request/src/index.ts b/packages/request/src/index.ts index 5c40139..e981647 100644 --- a/packages/request/src/index.ts +++ b/packages/request/src/index.ts @@ -59,7 +59,7 @@ req.use(async (ctx, next) => { // 先判断Grpc-Metadata-Errorx-Message let errMsg = res.headers.get('Grpc-Metadata-Errorx-Message'); if (errMsg) { - errMsg = window?.utf8?.decode(base64.decode(errMsg)); + errMsg = base64.decode(errMsg) // 后判断 body中的message } else if (!errMsg && get(body, 'message')) { errMsg = `${get(body, 'message')}`; diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index 4b45684..0843b80 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,5 +1,11 @@ # @zhst/types +## 0.3.0 + +### Minor Changes + +- feat: 初始化项目包 + ## 0.2.4 ### Patch Changes diff --git a/packages/types/index.d.ts b/packages/types/index.d.ts index f04db81..890324e 100644 --- a/packages/types/index.d.ts +++ b/packages/types/index.d.ts @@ -141,7 +141,7 @@ export interface IScreenshotButtonProp { getCropInfo: () => Promise; setShowCrop: React.Dispatch>; cropType: typeof cropType[number]; - selectAlgorithmVersion: number | null; + selectAlgorithmVersion?: number | null; } export interface AlignType { @@ -275,4 +275,5 @@ export type IOdRectOrigin { featureString: any[] } subObjects: any[] + objects: any[] } diff --git a/packages/types/package.json b/packages/types/package.json index 42c5ff3..b04dddb 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -1,6 +1,6 @@ { "name": "@zhst/types", - "version": "0.2.4", + "version": "0.3.0", "description": "变量定义库", "keywords": [ "types", @@ -13,14 +13,14 @@ "main": "", "typings": "index.d.ts", "exports": { - ".": { - "types": { - "default": "./index.d.ts" - } - }, - "./user": "./user.d.ts", - "./BigImageModal": "./BigImageModal.d.ts", - "./package.json": "./package.json" + ".": { + "types": { + "default": "./index.d.ts" + } + }, + "./user": "./user.d.ts", + "./BigImageModal": "./BigImageModal.d.ts", + "./package.json": "./package.json" }, "scripts": { "build": "father build" @@ -29,6 +29,5 @@ "access": "public", "registry": "http://10.0.0.77:4874" }, - "dependencies": { - } + "dependencies": {} } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index adf155e..17d36c6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -80,18 +80,12 @@ importers: antd: specifier: ^5.12.5 version: 5.12.5(react-dom@18.2.0)(react@18.2.0) - base-64: - specifier: ^1.0.0 - version: 1.0.0 classnames: specifier: ^2.5.1 version: 2.5.1 rc-util: specifier: ^5.38.1 version: 5.38.1(react-dom@18.2.0)(react@18.2.0) - umi-request: - specifier: ^1.4.0 - version: 1.4.0 devDependencies: '@zhst/types': specifier: workspace:^