text
stringlengths
2
1.05M
export const CheckSquareOutline = { name: 'check-square', theme: 'outline', icon: '<svg viewBox="64 64 896 896" focusable="false"><path d="M433.1 657.7a31.8 31.8 0 0051.7 0l210.6-292c3.8-5.3 0-12.7-6.5-12.7H642c-10.2 0-19.9 4.9-25.9 13.3L459 584.3l-71.2-98.8c-6-8.3-15.6-13.3-25.9-13.3H315c-6.5 0-10.3 7.4-6.5 12.7l124.6 172.8z" /><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z" /></svg>' }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiQ2hlY2tTcXVhcmVPdXRsaW5lLmpzIiwic291cmNlUm9vdCI6Ii4uLy4uLy4uLy4uL3NyYy9pY29ucy8iLCJzb3VyY2VzIjpbIm91dGxpbmUvQ2hlY2tTcXVhcmVPdXRsaW5lLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUVBLE1BQU0sQ0FBQyxNQUFNLGtCQUFrQixHQUFtQjtJQUM5QyxJQUFJLEVBQUUsY0FBYztJQUNwQixLQUFLLEVBQUUsU0FBUztJQUNoQixJQUFJLEVBQUUsb1pBQW9aO0NBQzdaLENBQUEiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBJY29uRGVmaW5pdGlvbiB9IGZyb20gJ0BhbnQtZGVzaWduL2ljb25zLWFuZ3VsYXInO1xuXG5leHBvcnQgY29uc3QgQ2hlY2tTcXVhcmVPdXRsaW5lOiBJY29uRGVmaW5pdGlvbiA9IHtcbiAgICBuYW1lOiAnY2hlY2stc3F1YXJlJyxcbiAgICB0aGVtZTogJ291dGxpbmUnLFxuICAgIGljb246ICc8c3ZnIHZpZXdCb3g9XCI2NCA2NCA4OTYgODk2XCIgZm9jdXNhYmxlPVwiZmFsc2VcIj48cGF0aCBkPVwiTTQzMy4xIDY1Ny43YTMxLjggMzEuOCAwIDAwNTEuNyAwbDIxMC42LTI5MmMzLjgtNS4zIDAtMTIuNy02LjUtMTIuN0g2NDJjLTEwLjIgMC0xOS45IDQuOS0yNS45IDEzLjNMNDU5IDU4NC4zbC03MS4yLTk4LjhjLTYtOC4zLTE1LjYtMTMuMy0yNS45LTEzLjNIMzE1Yy02LjUgMC0xMC4zIDcuNC02LjUgMTIuN2wxMjQuNiAxNzIuOHpcIiAvPjxwYXRoIGQ9XCJNODgwIDExMkgxNDRjLTE3LjcgMC0zMiAxNC4zLTMyIDMydjczNmMwIDE3LjcgMTQuMyAzMiAzMiAzMmg3MzZjMTcuNyAwIDMyLTE0LjMgMzItMzJWMTQ0YzAtMTcuNy0xNC4zLTMyLTMyLTMyem0tNDAgNzI4SDE4NFYxODRoNjU2djY1NnpcIiAvPjwvc3ZnPidcbn0iXX0=
'use strict'; 'use-strict'; var _powerAssertVisitorKeys = '{"ArrayExpression":["elements"],"AssignmentExpression":["left","right"],"BinaryExpression":["left","right"],"Directive":["value"],"DirectiveLiteral":[],"BlockStatement":["directives","body"],"BreakStatement":["label"],"CallExpression":["callee","arguments"],"CatchClause":["param","body"],"ConditionalExpression":["test","consequent","alternate"],"ContinueStatement":["label"],"DebuggerStatement":[],"DoWhileStatement":["test","body"],"EmptyStatement":[],"ExpressionStatement":["expression"],"File":["program"],"ForInStatement":["left","right","body"],"ForStatement":["init","test","update","body"],"FunctionDeclaration":["id","params","body","returnType","typeParameters"],"FunctionExpression":["id","params","body","returnType","typeParameters"],"Identifier":["typeAnnotation"],"IfStatement":["test","consequent","alternate"],"LabeledStatement":["label","body"],"StringLiteral":[],"NumericLiteral":[],"NullLiteral":[],"BooleanLiteral":[],"RegExpLiteral":[],"LogicalExpression":["left","right"],"MemberExpression":["object","property"],"NewExpression":["callee","arguments"],"Program":["directives","body"],"ObjectExpression":["properties"],"ObjectMethod":["key","params","body","decorators","returnType","typeParameters"],"ObjectProperty":["key","value","decorators"],"RestElement":["argument","typeAnnotation"],"ReturnStatement":["argument"],"SequenceExpression":["expressions"],"SwitchCase":["test","consequent"],"SwitchStatement":["discriminant","cases"],"ThisExpression":[],"ThrowStatement":["argument"],"TryStatement":["block","handler","finalizer"],"UnaryExpression":["argument"],"UpdateExpression":["argument"],"VariableDeclaration":["declarations"],"VariableDeclarator":["id","init"],"WhileStatement":["test","body"],"WithStatement":["object","body"],"AssignmentPattern":["left","right"],"ArrayPattern":["elements","typeAnnotation"],"ArrowFunctionExpression":["params","body","returnType","typeParameters"],"ClassBody":["body"],"ClassDeclaration":["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators"],"ClassExpression":["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators"],"ExportAllDeclaration":["source"],"ExportDefaultDeclaration":["declaration"],"ExportNamedDeclaration":["declaration","specifiers","source"],"ExportSpecifier":["local","exported"],"ForOfStatement":["left","right","body"],"ImportDeclaration":["specifiers","source"],"ImportDefaultSpecifier":["local"],"ImportNamespaceSpecifier":["local"],"ImportSpecifier":["local","imported"],"MetaProperty":["meta","property"],"ClassMethod":["key","params","body","decorators","returnType","typeParameters"],"ObjectPattern":["properties","typeAnnotation"],"SpreadElement":["argument"],"Super":[],"TaggedTemplateExpression":["tag","quasi"],"TemplateElement":[],"TemplateLiteral":["quasis","expressions"],"YieldExpression":["argument"],"AnyTypeAnnotation":[],"ArrayTypeAnnotation":["elementType"],"BooleanTypeAnnotation":[],"BooleanLiteralTypeAnnotation":[],"NullLiteralTypeAnnotation":[],"ClassImplements":["id","typeParameters"],"ClassProperty":["key","value","typeAnnotation","decorators"],"DeclareClass":["id","typeParameters","extends","body"],"DeclareFunction":["id"],"DeclareInterface":["id","typeParameters","extends","body"],"DeclareModule":["id","body"],"DeclareModuleExports":["typeAnnotation"],"DeclareTypeAlias":["id","typeParameters","right"],"DeclareOpaqueType":["id","typeParameters","supertype"],"DeclareVariable":["id"],"DeclareExportDeclaration":["declaration","specifiers","source"],"ExistentialTypeParam":[],"FunctionTypeAnnotation":["typeParameters","params","rest","returnType"],"FunctionTypeParam":["name","typeAnnotation"],"GenericTypeAnnotation":["id","typeParameters"],"InterfaceExtends":["id","typeParameters"],"InterfaceDeclaration":["id","typeParameters","extends","body"],"IntersectionTypeAnnotation":["types"],"MixedTypeAnnotation":[],"EmptyTypeAnnotation":[],"NullableTypeAnnotation":["typeAnnotation"],"NumericLiteralTypeAnnotation":[],"NumberTypeAnnotation":[],"StringLiteralTypeAnnotation":[],"StringTypeAnnotation":[],"ThisTypeAnnotation":[],"TupleTypeAnnotation":["types"],"TypeofTypeAnnotation":["argument"],"TypeAlias":["id","typeParameters","right"],"OpaqueType":["id","typeParameters","impltype","supertype"],"TypeAnnotation":["typeAnnotation"],"TypeCastExpression":["expression","typeAnnotation"],"TypeParameter":["bound"],"TypeParameterDeclaration":["params"],"TypeParameterInstantiation":["params"],"ObjectTypeAnnotation":["properties","indexers","callProperties"],"ObjectTypeCallProperty":["value"],"ObjectTypeIndexer":["id","key","value"],"ObjectTypeProperty":["key","value"],"ObjectTypeSpreadProperty":["argument"],"QualifiedTypeIdentifier":["id","qualification"],"UnionTypeAnnotation":["types"],"VoidTypeAnnotation":[],"JSXAttribute":["name","value"],"JSXClosingElement":["name"],"JSXElement":["openingElement","children","closingElement"],"JSXEmptyExpression":[],"JSXExpressionContainer":["expression"],"JSXSpreadChild":["expression"],"JSXIdentifier":[],"JSXMemberExpression":["object","property"],"JSXNamespacedName":["namespace","name"],"JSXOpeningElement":["name","attributes"],"JSXSpreadAttribute":["argument"],"JSXText":[],"Noop":[],"ParenthesizedExpression":["expression"],"AwaitExpression":["argument"],"ForAwaitStatement":["left","right","body"],"BindExpression":["object","callee"],"Import":[],"Decorator":["expression"],"DoExpression":["body"],"ExportDefaultSpecifier":["exported"],"ExportNamespaceSpecifier":["exported"],"RestProperty":["argument"],"SpreadProperty":["argument"]}', _powerAssertRecorder = function () { function PowerAssertRecorder() { this.captured = []; } PowerAssertRecorder.prototype._capt = function _capt(value, espath) { this.captured.push({ value: value, espath: espath }); return value; }; PowerAssertRecorder.prototype._expr = function _expr(value, source) { var capturedValues = this.captured; this.captured = []; return { powerAssertContext: { value: value, events: capturedValues }, source: source }; }; return PowerAssertRecorder; }(); const test = require('ava'); const sinon = require('sinon'); const proxyquire = require('proxyquire'); let config = { logging: function () {} }; let MetricStub = { belongsTo: sinon.spy() // un spy es un funcion que nos dice datos sobre la funcion, es un chicmoso vamos }; let AgentStub = null; let db = null; let sandbox = null; test.beforeEach(async () => { sandbox = sinon.sandbox.create(); AgentStub = { //un ambiente especifico que solo funciona para este caso en particular hasMany: sandbox.spy() }; const setupDatabase = proxyquire('../', { './models/agent': () => AgentStub, // las mismas rutas que las que estan e declaradas en index.js './models/metric': () => MetricStub }); db = await setupDatabase(config); }); test.afterEach(t => { sandbox && sinon.sandbo0x.restore(); }); test('Agent', t => { var _rec = new _powerAssertRecorder(); // verificacion de que Agent exista t.truthy(_rec._expr(_rec._capt(_rec._capt(db, 'arguments/0/object').Agent, 'arguments/0'), { content: 't.truthy(db.Agent, \'Agent service should exist\')', filepath: 'tests\\agent-tests.js', line: 42, ast: '{"type":"CallExpression","callee":{"type":"MemberExpression","object":{"type":"Identifier","name":"t","range":[0,1]},"property":{"type":"Identifier","name":"truthy","range":[2,8]},"computed":false,"range":[0,8]},"arguments":[{"type":"MemberExpression","object":{"type":"Identifier","name":"db","range":[9,11]},"property":{"type":"Identifier","name":"Agent","range":[12,17]},"computed":false,"range":[9,17]},{"type":"StringLiteral","value":"Agent service should exist","range":[19,47]}],"range":[0,48]}', tokens: '[{"type":{"label":"name"},"value":"t","range":[0,1]},{"type":{"label":"."},"range":[1,2]},{"type":{"label":"name"},"value":"truthy","range":[2,8]},{"type":{"label":"("},"range":[8,9]},{"type":{"label":"name"},"value":"db","range":[9,11]},{"type":{"label":"."},"range":[11,12]},{"type":{"label":"name"},"value":"Agent","range":[12,17]},{"type":{"label":","},"range":[17,18]},{"type":{"label":"string"},"value":"Agent service should exist","range":[19,47]},{"type":{"label":")"},"range":[47,48]}]', visitorKeys: _powerAssertVisitorKeys }), 'Agent service should exist'); // si se resulve el valor a verdadero }); test.serial('Setup', t => { var _rec2 = new _powerAssertRecorder(), _rec3 = new _powerAssertRecorder(); t.true(_rec2._expr(_rec2._capt(_rec2._capt(_rec2._capt(AgentStub, 'arguments/0/object/object').hasMany, 'arguments/0/object').called, 'arguments/0'), { content: 't.true(AgentStub.hasMany.called, \'AgentModel.hasMany fue ejecutada\')', filepath: 'tests\\agent-tests.js', line: 46, ast: '{"type":"CallExpression","callee":{"type":"MemberExpression","object":{"type":"Identifier","name":"t","range":[0,1]},"property":{"type":"Identifier","name":"true","range":[2,6]},"computed":false,"range":[0,6]},"arguments":[{"type":"MemberExpression","object":{"type":"MemberExpression","object":{"type":"Identifier","name":"AgentStub","range":[7,16]},"property":{"type":"Identifier","name":"hasMany","range":[17,24]},"computed":false,"range":[7,24]},"property":{"type":"Identifier","name":"called","range":[25,31]},"computed":false,"range":[7,31]},{"type":"StringLiteral","value":"AgentModel.hasMany fue ejecutada","range":[33,67]}],"range":[0,68]}', tokens: '[{"type":{"label":"name"},"value":"t","range":[0,1]},{"type":{"label":"."},"range":[1,2]},{"type":{"label":"true"},"value":"true","range":[2,6]},{"type":{"label":"("},"range":[6,7]},{"type":{"label":"name"},"value":"AgentStub","range":[7,16]},{"type":{"label":"."},"range":[16,17]},{"type":{"label":"name"},"value":"hasMany","range":[17,24]},{"type":{"label":"."},"range":[24,25]},{"type":{"label":"name"},"value":"called","range":[25,31]},{"type":{"label":","},"range":[31,32]},{"type":{"label":"string"},"value":"AgentModel.hasMany fue ejecutada","range":[33,67]},{"type":{"label":")"},"range":[67,68]}]', visitorKeys: _powerAssertVisitorKeys }), 'AgentModel.hasMany fue ejecutada'); t.true(_rec3._expr(_rec3._capt(_rec3._capt(_rec3._capt(MetricStub, 'arguments/0/object/object').belongsTo, 'arguments/0/object').called, 'arguments/0'), { content: 't.true(MetricStub.belongsTo.called, \'MetricModel.belongsTo fue ejecutada\')', filepath: 'tests\\agent-tests.js', line: 47, ast: '{"type":"CallExpression","callee":{"type":"MemberExpression","object":{"type":"Identifier","name":"t","range":[0,1]},"property":{"type":"Identifier","name":"true","range":[2,6]},"computed":false,"range":[0,6]},"arguments":[{"type":"MemberExpression","object":{"type":"MemberExpression","object":{"type":"Identifier","name":"MetricStub","range":[7,17]},"property":{"type":"Identifier","name":"belongsTo","range":[18,27]},"computed":false,"range":[7,27]},"property":{"type":"Identifier","name":"called","range":[28,34]},"computed":false,"range":[7,34]},{"type":"StringLiteral","value":"MetricModel.belongsTo fue ejecutada","range":[36,73]}],"range":[0,74]}', tokens: '[{"type":{"label":"name"},"value":"t","range":[0,1]},{"type":{"label":"."},"range":[1,2]},{"type":{"label":"true"},"value":"true","range":[2,6]},{"type":{"label":"("},"range":[6,7]},{"type":{"label":"name"},"value":"MetricStub","range":[7,17]},{"type":{"label":"."},"range":[17,18]},{"type":{"label":"name"},"value":"belongsTo","range":[18,27]},{"type":{"label":"."},"range":[27,28]},{"type":{"label":"name"},"value":"called","range":[28,34]},{"type":{"label":","},"range":[34,35]},{"type":{"label":"string"},"value":"MetricModel.belongsTo fue ejecutada","range":[36,73]},{"type":{"label":")"},"range":[73,74]}]', visitorKeys: _powerAssertVisitorKeys }), 'MetricModel.belongsTo fue ejecutada'); }); //# sourceMappingURL=C:\Users\Angel Barusta\Desktop\nodejs\iot_nodejs\node_modules\.cache\ava\932928d07f52a07a8581727c215a5828.js.map
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Advancement of lastIndex es6id: 21.2.5.2.2 info: | 21.2.5.2.2 Runtime Semantics: RegExpBuiltinExec ( R, S ) [...] 12. Let flags be the value of R’s [[OriginalFlags]] internal slot. 13. If flags contains "u", let fullUnicode be true, else let fullUnicode be false. [...] 15. Repeat, while matchSucceeded is false [...] c. If r is failure, then [...] ii. Let lastIndex be AdvanceStringIndex(S, lastIndex, fullUnicode). ---*/ assert.sameValue(/\udf06/u.exec('\ud834\udf06'), null);
const path = require('path') const {VueLoaderPlugin} = require('vue-loader') const HTMLWebpackPlugin = require('html-webpack-plugin'); const site = path.join(__dirname, '../../../site'); module.exports = { entry: path.join(site, 'main.ts'), module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/}, { test: /\.jsx$/, use: 'babel-loader'}, { test: /\.vue$/, use: 'vue-loader' }, { test: /\.tsx$/, use: ['babel-loader','ts-loader']}, { test: /\.ts$/, use: [ 'babel-loader', { loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/], } }, ] }, { test: /\.css$/, use: ['style-loader', 'css-loader']}, { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader']}, ] }, resolve: { extensions: ['.js', '.ts', '.tsx', '.vue'], alias: { // this isn't technically needed, since the default `vue` entry for bundlers // is a simple `export * from '@vue/runtime-dom`. However having this // extra re-export somehow causes webpack to always invalidate the module // on the first HMR update and causes the page to reload. 'vue': '@vue/runtime-dom' } }, plugins: [ new VueLoaderPlugin(), new HTMLWebpackPlugin({ template: path.resolve(site, './public/index.html') }) ], };
// ========================================================================== // Animation utils // ========================================================================== import is from './is'; export const transitionEndEvent = (() => { const element = document.createElement('span'); const events = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend', }; const type = Object.keys(events).find(event => element.style[event] !== undefined); return is.string(type) ? events[type] : false; })(); // Force repaint of element export function repaint(element, delay) { setTimeout(() => { try { // eslint-disable-next-line no-param-reassign element.hidden = true; // eslint-disable-next-line no-unused-expressions element.offsetHeight; // eslint-disable-next-line no-param-reassign element.hidden = false; } catch (e) { // Do nothing } }, delay); }
var searchData= [ ['mat',['mat',['../structsalle__s.html#ad9934630b58b551f8f185dead2006ba6',1,'salle_s']]] ];
KB.on('dom.ready', function() { function savePosition(subtaskId, position) { var url = $(".subtasks-table").data("save-position-url"); $.ajax({ cache: false, url: url, contentType: "application/json", type: "POST", processData: false, data: JSON.stringify({ "subtask_id": subtaskId, "position": position }) }); } $(".draggable-row-handle").mouseenter(function() { $(this).parent().parent().addClass("draggable-item-hover"); }).mouseleave(function() { $(this).parent().parent().removeClass("draggable-item-hover"); }); $(".subtasks-table tbody").sortable({ forcePlaceholderSize: true, handle: "td:first i", helper: function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }, stop: function(event, ui) { var subtask = ui.item; subtask.removeClass("draggable-item-selected"); savePosition(subtask.data("subtask-id"), subtask.index() + 1); }, start: function(event, ui) { ui.item.addClass("draggable-item-selected"); } }).disableSelection(); });
import { createSlice } from '@reduxjs/toolkit'; import reducers from './boardsReducers'; import extraReducers from './boardsThunks'; import getInitialState from './boardsInitialState'; export const boardsSlice = createSlice({ name: 'boards', initialState: getInitialState(), reducers, extraReducers, }); export const { tileSet, previewSet, previewRemoved, orientationUpdated, boardsReset, } = boardsSlice.actions; export * from './boardsThunks'; export * from './boardsSelectors'; export default boardsSlice.reducer;
class item { // o Math serve para não ter a chance de 2 itens terem o mesmo Id quando são chamados pelo localStorage static lastId = 0 + Math.random() * 1000; constructor(text, habit, priority, day, month, year) { this.id = item.lastId++; this.text = text; this.done = false; this.habit = habit; this.priority = priority; this.day = day; this.month = month; this.year = year; } } export default item;
/* Copyright (c) 2018-2020 Uber Technologies, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ // @flow import * as React from 'react'; import {ProgressBarRounded, SIZE} from '../index.js'; export default function Scenario() { return ( <React.Fragment> <ProgressBarRounded progress={0.5} size={SIZE.small} animate={false} inline /> <ProgressBarRounded progress={0.5} size={SIZE.medium} animate={false} inline /> <ProgressBarRounded progress={0.5} size={SIZE.large} animate={false} inline /> </React.Fragment> ); }
import React, { useCallback, useImperativeHandle, useMemo, useRef, useState, } from 'react'; import clsx from 'clsx'; import getScrollbarWidth, { contains, convertToArray, invoke, isNil, isNumber, validate, } from '../Utils'; import Checkbox from '../Checkbox'; import Radio from '../Radio'; import useInternalState from '../common/useInternalState'; import {initStore} from '../common/Store'; import {checkScrollBar, filterLeaves, SortOrder} from './TableUtils'; import BodyCell from './BodyCell'; import TableHead from './TableHead'; import * as PropTypes from "prop-types"; import Element from "../common/Element"; const Type = { normal: 'normal', striped: 'striped', simple: 'simple', }; const CheckType = { checkbox: 'checkbox', radio: 'radio', }; const SortComparator = (a, b) => a === b ? 0 : (a < b ? 1 : -1); //by desc const FilterComparator = (filteredValues, row, cell) => { for (let value of filteredValues) { if (row[cell.paramName].toString().includes(value.toString())) { return true; } } return false; }; const Table = React.forwardRef((props, ref) => { const { instanceRef, extraClassName, className = 'table', children, type = Type.normal, hover = false, hasBorder = true, loadData, cells, hasBox = false, checkable = false, checkType = CheckType.checkbox, canCheckAll = checkType === CheckType.checkbox, onCheckChange, onCheckAll, defaultCheckedRows, checkedRows, highlightCheckedRow = true, defaultSortComparator = SortComparator, defaultSortOrder = SortOrder.desc, onSort, sortOrder, //format: {key: key, order: 'asc'} //for filter defaultOkText = 'OK', defaultResetText = 'Reset', defaultFilterComparator = FilterComparator, // filteredItems, //[value] onFilter, scrollY = false, bodyHeight = 250, //number scrollX = false, bodyWidth, //number ...otherProps } = props; const isLoadDataDefined = !isNil(loadData); const isCellsDefined = !isNil(cells); const isJsonData = isLoadDataDefined || isCellsDefined; if (isJsonData) { validate(isLoadDataDefined, 'the loadData should be provided'); validate(isCellsDefined, 'the cells should be provided'); } const [checkedRowKeys, setChecked, customCheck] = useInternalState({ props, stateName: 'checkedRows', defaultState: convertToArray(defaultCheckedRows), state: convertToArray(checkedRows), }); //a reference to popup so that we can close the popup by calling the instance's method const popupRef = useRef(null); //The sort details of the columns, {key: paramName, order: asc/desc, sorter: (data)=>{...]} const [sortedState, setSortedState] = useState(); //active the filter popup, the format is {key: paramName}, only one filter popup can display at same time const [activeFilter, setActiveFilter] = useState(null); //[{filterValue: v, fc}}], fc means filterComparator const [filterParams, setFilterParams] = useState([]); //init a internal store //{ checkedValues: {key: [values]} , the key corresponds the paramName const [store] = useState(() => initStore({ checkedValues: {}, })); const scrollHeadRef = useRef(); const scrollBodyRef = useRef(); const scrollBarWidthRef = useRef(getScrollbarWidth()); useImperativeHandle(instanceRef, () => ({ clearSort: () => { setSortedState(null); }, clearFilter: () => { setActiveFilter(null); setFilterParams([]); store.setState({checkedValues: {}}); }, clearAll: () => { instanceRef.current.clearSort(); instanceRef.current.clearFilter(); }, }), [instanceRef, store]); //for cells definition const cellsData = useMemo(() => convertToArray(cells), [cells]); //the table data const rowData = useMemo(() => { var data = convertToArray(loadData); if (sortedState) { data = sortedState.sorter(data); } if (filterParams.length > 0) { filterParams.forEach(param => { data = data.filter(param.fc); }); } return [...data]; }, [filterParams, loadData, sortedState]); const isCheckbox = checkType === CheckType.checkbox; const head = <TableHead cells={cells} setChecked={setChecked} checkable={checkable} canCheckAll={canCheckAll} isCheckbox={isCheckbox} rowData={rowData} cellsData={cellsData} checkedRowKeys={checkedRowKeys} checkedRows={checkedRows} onCheckAll={onCheckAll} defaultSortComparator={defaultSortComparator} defaultSortOrder={defaultSortOrder} sortOrder={sortOrder} sortedState={sortedState} setSortedState={setSortedState} onSort={onSort} scrollHeadRef={scrollHeadRef} activeFilter={activeFilter} setFilterParams={setFilterParams} filterParams={filterParams} setActiveFilter={setActiveFilter} store={store} defaultOkText={defaultOkText} defaultResetText={defaultResetText} defaultFilterComparator={defaultFilterComparator} popupRef={popupRef} scrollY={scrollY} scrollBarWidthRef={scrollBarWidthRef} onCheckChange={onCheckChange}/>; const fixedHead = useMemo(() => { return head; }, [head]); const getHead = useCallback(() => { if (scrollY) { return fixedHead; } return head; }, [scrollY, fixedHead, head]); const checkOneHandler = useCallback((row, nextCheck, e) => { if (!customCheck) { if (nextCheck) { if (isCheckbox) { setChecked(pre => [...pre.filter(k => k !== row.key), row.key]); } else { setChecked(pre => [row.key]); } } else { if (isCheckbox) { setChecked(pre => [...pre.filter(k => k !== row.key)]); } else { setChecked(pre => []); } } } onCheckChange && onCheckChange(row, nextCheck, e); }, [customCheck, isCheckbox, onCheckChange, setChecked]); const getCheckForRow = useCallback((row, isRowChecked) => { if (checkable) { function checkRow(value, e) { checkOneHandler(row, value, e); } return <td className="cell-check"> {isCheckbox ? <Checkbox checked={isRowChecked} onChange={checkRow}/> : <Radio value={true} checked={isRowChecked} onChange={checkRow}/>} </td>; } return null; }, [checkOneHandler, checkable, isCheckbox]); const body = useMemo(() => { const realCellsData = filterLeaves(cellsData); return <tbody> { rowData.map((row, index) => { const isRowChecked = contains(row.key, checkedRowKeys); const selectTd = getCheckForRow(row, isRowChecked); const trClsName = clsx({ 'hl-tr': checkable && isRowChecked && highlightCheckedRow, }); return <tr className={trClsName} key={row.key}> {selectTd} { realCellsData.map((cell, i) => { let content = row[cell.paramName]; if (cell.format) { content = invoke(cell.format, content, row, index); } return <BodyCell key={row.key + '-' + i} scrollHeadRef={scrollHeadRef} store={store} cell={cell} tdKey={row.key + '-' + i} content={content}/>; }) } </tr>; }) } </tbody>; }, [ cellsData, checkable, checkedRowKeys, getCheckForRow, highlightCheckedRow, rowData, store]); const getColGroups = useCallback((isHead) => { let leaves = []; for (let cell of cellsData) { let nodes = [cell]; while (nodes.length > 0) { const node = nodes.shift(); if (isNil(node.children)) { leaves.push(node); } else { nodes = nodes.concat(node.children); } } } //todo if (!isNil(bodyWidth)) { let totalWidth = 0; const leafInfoArray = []; leaves.forEach((leaf, i) => { if (isNumber(leaf.width)) { totalWidth += parseInt(leaf.width); } else { leafInfoArray.push({position: i}); } }); const size = leafInfoArray.length; const leftWidth = bodyWidth - totalWidth; const leftThWidth = size > 0 ? Math.floor(leftWidth / size) : -1; leafInfoArray.forEach(info => { if (leftThWidth > 0) { // leaves[info.position].width = leftThWidth; } }); } var cols = leaves.map((c, index) => <col key={c.width + '-' + index} style={{ width: isNumber(c.width) ? c.width + 'px' : c.width, }}/>); if (scrollY && isHead) { cols.push(<col key="scroll-y-col" style={{width: scrollBarWidthRef.current}}/>); } return <> <colgroup> {checkable && <col className="col-check"/>} {cols} </colgroup> </>; }, [bodyWidth, cellsData, checkable, scrollY]); const clsName = clsx(extraClassName, className, type, { 'hover': hover, 'clear-border': !hasBorder, 'global-with-box': hasBox, }); //scroll the body and make sure the head scroll as well as same distance const doScrollX = useCallback((e) => { scrollHeadRef.current.scrollLeft = e.target.scrollLeft; store.setState(checkScrollBar(scrollHeadRef)); }, [store]); const getDataTable = useCallback((tblClsName, bodyStyle, others, hasHead) => { return <table className={tblClsName} style={bodyStyle} {...others} ref={ref}> {getColGroups(false)} {hasHead && isJsonData && getHead()} {isJsonData && body} {!isJsonData && children} </table>; }, [body, children, getColGroups, getHead, isJsonData, ref]); const getBody = useCallback(() => { const {style, ...others} = otherProps; const bodyStyle = {...style, width: bodyWidth}; //the width of head should be greater than the body's width, it should plus the width of the scroll bar let headWidth; if (!isNil(bodyWidth)) { headWidth = bodyWidth + scrollBarWidthRef.current; /* try { var groups = /(\d+)(.*)/.exec(bodyWidth); headWidth = parseInt(groups[1]) + scrollBarWidthRef.current + groups[2]; } catch (e) { validate(false, `the bodyWidth '${bodyWidth}' is invalid`); }*/ } const headStyle = {...style}; if (!isNil(headWidth)) { headStyle.width = headWidth; } if (scrollY) { // bodyStyle.height = bodyHeight; } if (scrollY) { return <> <div className={`table-wrapper`}> { isJsonData && <div className="head-wrapper" ref={scrollHeadRef}> <table className={`${clsName} scroll-head`} style={headStyle} {...others}> {getColGroups(true)} {getHead()} </table> </div> } <div style={{maxHeight: bodyHeight}} className={'scroll-wrapper'} ref={scrollBodyRef} onScroll={doScrollX}> { getDataTable(clsName, bodyStyle, others, false) } </div> </div> </>; } return <div className={`table-wrapper`}> { getDataTable(clsName, bodyStyle, others, true) } </div>; }, [ otherProps, bodyWidth, scrollY, getDataTable, clsName, bodyHeight, isJsonData, getColGroups, getHead, doScrollX]); return getBody(); }); Table.propTypes = { extraClassName: PropTypes.string, className: PropTypes.string, instanceRef: PropTypes.oneOfType([ PropTypes.func, PropTypes.shape({current: PropTypes.instanceOf(Element)}), ]), type: PropTypes.oneOf(Object.keys(Type)), hover: PropTypes.bool, hasBorder: PropTypes.bool, loadData: PropTypes.oneOfType( [PropTypes.array, PropTypes.func, PropTypes.object]), cells: PropTypes.arrayOf(PropTypes.shape({ key: PropTypes.any, head: PropTypes.node, paramName: PropTypes.string, autoEllipsis: PropTypes.bool, fixed: PropTypes.oneOf(['left', 'right']), sortable: PropTypes.bool, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), filterable: PropTypes.bool, filterConfig: PropTypes.shape({ filterItems: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.node, value: PropTypes.any })) }), })), hasBox: PropTypes.bool, checkable: PropTypes.bool, checkType: PropTypes.oneOf(Object.keys(CheckType)), canCheckAll: PropTypes.bool, onCheckChange: PropTypes.func, onCheckAll: PropTypes.func, defaultCheckedRows: PropTypes.oneOfType( [PropTypes.string, PropTypes.array]), checkedRows: PropTypes.oneOfType( [PropTypes.string, PropTypes.array]), highlightCheckedRow: PropTypes.bool, defaultSortComparator: PropTypes.func, defaultSortOrder: PropTypes.string, onSort: PropTypes.func, sortOrder: PropTypes.shape({ key: PropTypes.any, order: PropTypes.string }), defaultOkText: PropTypes.string, defaultResetText: PropTypes.string, defaultFilterComparator: PropTypes.func, // filteredItems: PropTypes.arrayOf(PropTypes.string), onFilter: PropTypes.func, scrollY: PropTypes.bool, bodyHeight: PropTypes.number, scrollX: PropTypes.bool, bodyWidth: PropTypes.number } export default Table;
import React from "react"; const Column = props => { const size = props.size .split(" ") .map(size => "col-" + size) .join(" "); return <div className={size}>{props.children}</div>; }; export default Column;
({ doInit: function(component, event, helper) { console.log('doInit'); var eventParams = event.getParams(); if(eventParams.changeType === "LOADED") { component.get("v.recordInfo"); // record is loaded (render other component which needs record data value) console.log("Record is loaded successfully."); } else if(eventParams.changeType === "CHANGED") { // record is changed } else if(eventParams.changeType === "REMOVED") { // record is deleted } else if(eventParams.changeType === "ERROR") { // there’s an error while loading, saving, or deleting the record } var clsStopwatch = function() { var startAt = startAt || 0; var lapTime = lapTime || 0; var now = function() { return (new Date()).getTime(); }; this.start = function() { startAt = startAt ? startAt : now(); }; this.stop = function() { lapTime = startAt ? lapTime + now() - startAt : lapTime; startAt = 0; }; this.reset = function() { lapTime = 0; startAt = 0; }; this.time = function() { return lapTime + (startAt ? now() - startAt : 0); }; }; var x = new clsStopwatch(); component.set("v.stopwatch", x); var clocktimer = setInterval(function() { helper.updateStatus(component, event); }, 1); var theCase = component.get('v.simpleCase'); if(theCase.Status === 'Closed') { component.set('v.disabled',true); $A.util.addClass(component.find("timerDiv"), "slds-hide"); component.set('v.playing',false); } else { component.set('v.disabled',false); $A.util.removeClass(component.find("timerDiv"), "slds-hide"); if(component.get('v.autoStart') === 'True') { x.start(); component.set('v.playing',true); component.set('v.recording',true); } else { component.set('v.playing',false); x.stop(); } } helper.loadSessions(component, event); }, onClick : function(component, event, helper) { var clocktimer; var id = event.target.id; var x = component.get("v.stopwatch"); switch(id){ case "start": component.set('v.playing',true); component.set('v.recording',true); clocktimer = setInterval(function() { helper.updateStatus(component, event); }, 1); x.start(); break; case "stop": component.set('v.playing',false); x.stop(); clearInterval(clocktimer); helper.updateStatus(component, event); break; default: stop(); break; } }, update : function (component, event, helper) { // Get the new hash from the event var loc = event.getParam("token"); console.log("Creating Session: update"); console.log(loc); helper.createSession(component, event); // Do something else }, handleSaveSession: function(component, event, helper) { console.log('start save session'); if(helper.validateSessionForm(component)) { console.log('after conditional helper'); // Prepare the action to create the new session var saveSessionAction = component.get("c.newSessionManual"); saveSessionAction.setParams({ "caseId" : component.get("v.recordId"), "timeVal" : component.get("v.manualDuration"), "theDate" : new Date(component.get("v.manualDate")).toJSON() }); // Configure the response handler for the action saveSessionAction.setCallback(this, function(response) { var state = response.getState(); if(state === "SUCCESS") { // Prepare a toast UI message var resultsToast = $A.get("e.force:showToast"); resultsToast.setParams({ "title": "Session Saved", "message": "The new session was created." }); // Update the UI: close panel, show toast, refresh case page $A.get("e.force:closeQuickAction").fire(); resultsToast.fire(); $A.get("e.force:refreshView").fire(); } else if (state === "ERROR") { console.log('Problem saving session, response state: ' + state); } else { console.log('Unknown problem, response state: ' + state); } }); // Send the request to create the new session $A.enqueueAction(saveSessionAction); helper.hideModal(component, event); } helper.loadSessions(component, event); }, newTime : function(component, event, helper) { $A.util.toggleClass(component.find("myModal"), "slds-hide"); }, cancelSession : function(component, event, helper) { helper.hideModal(component, event); } })
const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const WEBPACK_MODE = (typeof process.env.WEBPACK_MODE === 'undefined') ? "development" : process.env.WEBPACK_MODE; const OUTPUT_DIR= (typeof process.env.OUTPUT_DIR === 'undefined') ? path.resolve(__dirname, "dist") : process.env.OUTPUT_DIR; module.exports = { mode: WEBPACK_MODE, // values can be "development" or "production" entry: "./js/index.js", devtool: "source-map", output: { path: OUTPUT_DIR, filename: "bundle.js", webassemblyModuleFilename: "app.wasm", }, plugins: [ new CopyWebpackPlugin([{ from: "static_web" }]), ], };
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { SyncBailHook } = require("tapable"); const { RawSource } = require("webpack-sources"); const ChunkGraph = require("./ChunkGraph"); const Compilation = require("./Compilation"); const HotUpdateChunk = require("./HotUpdateChunk"); const NormalModule = require("./NormalModule"); const RuntimeGlobals = require("./RuntimeGlobals"); const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency"); const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency"); const ModuleHotDependency = require("./dependencies/ModuleHotDependency"); const HotModuleReplacementRuntimeModule = require("./hmr/HotModuleReplacementRuntimeModule"); const JavascriptParser = require("./javascript/JavascriptParser"); const { evaluateToIdentifier, evaluateToString, toConstantDependency } = require("./javascript/JavascriptParserHelpers"); const { find } = require("./util/SetHelpers"); const { compareModulesById } = require("./util/comparators"); /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Module")} Module */ /** * @typedef {Object} HMRJavascriptParserHooks * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback */ /** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */ const parserHooksMap = new WeakMap(); class HotModuleReplacementPlugin { /** * @param {JavascriptParser} parser the parser * @returns {HMRJavascriptParserHooks} the attached hooks */ static getParserHooks(parser) { if (!(parser instanceof JavascriptParser)) { throw new TypeError( "The 'parser' argument must be an instance of JavascriptParser" ); } let hooks = parserHooksMap.get(parser); if (hooks === undefined) { hooks = { hotAcceptCallback: new SyncBailHook(["expression", "requests"]), hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"]) }; parserHooksMap.set(parser, hooks); } return hooks; } constructor(options) { this.options = options || {}; this.multiStep = this.options.multiStep; this.fullBuildTimeout = this.options.fullBuildTimeout || 200; } /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { const multiStep = this.multiStep; const fullBuildTimeout = this.fullBuildTimeout; compiler.hooks.additionalPass.tapAsync( "HotModuleReplacementPlugin", callback => { if (multiStep) return setTimeout(callback, fullBuildTimeout); return callback(); } ); const addParserPlugins = (parser, parserOptions) => { const { hotAcceptCallback, hotAcceptWithoutCallback } = HotModuleReplacementPlugin.getParserHooks(parser); parser.hooks.expression .for("__webpack_hash__") .tap( "HotModuleReplacementPlugin", toConstantDependency(parser, `${RuntimeGlobals.getFullHash}()`, [ RuntimeGlobals.getFullHash ]) ); parser.hooks.evaluateTypeof .for("__webpack_hash__") .tap("HotModuleReplacementPlugin", evaluateToString("string")); parser.hooks.evaluateIdentifier.for("module.hot").tap( { name: "HotModuleReplacementPlugin", before: "NodeStuffPlugin" }, expr => { return evaluateToIdentifier( "module.hot", "module", () => ["hot"], true )(expr); } ); parser.hooks.call .for("module.hot.accept") .tap("HotModuleReplacementPlugin", expr => { const dep = new ModuleHotDependency(expr.callee.range, "accept"); dep.loc = expr.loc; parser.state.module.addDependency(dep); if (expr.arguments.length >= 1) { const arg = parser.evaluateExpression(expr.arguments[0]); let params = []; let requests = []; if (arg.isString()) { params = [arg]; } else if (arg.isArray()) { params = arg.items.filter(param => param.isString()); } if (params.length > 0) { params.forEach((param, idx) => { const request = param.string; const dep = new ModuleHotAcceptDependency(request, param.range); dep.optional = true; dep.loc = Object.create(expr.loc); dep.loc.index = idx; parser.state.module.addDependency(dep); requests.push(request); }); if (expr.arguments.length > 1) { hotAcceptCallback.call(expr.arguments[1], requests); parser.walkExpression(expr.arguments[1]); // other args are ignored return true; } else { hotAcceptWithoutCallback.call(expr, requests); return true; } } } return true; }); parser.hooks.call .for("module.hot.decline") .tap("HotModuleReplacementPlugin", expr => { const dep = new ModuleHotDependency(expr.callee.range, "decline"); dep.loc = expr.loc; parser.state.module.addDependency(dep); if (expr.arguments.length === 1) { const arg = parser.evaluateExpression(expr.arguments[0]); let params = []; if (arg.isString()) { params = [arg]; } else if (arg.isArray()) { params = arg.items.filter(param => param.isString()); } params.forEach((param, idx) => { const dep = new ModuleHotDeclineDependency( param.string, param.range ); dep.optional = true; dep.loc = Object.create(expr.loc); dep.loc.index = idx; parser.state.module.addDependency(dep); }); } return true; }); parser.hooks.expression .for("module.hot") .tap("HotModuleReplacementPlugin", expr => { const dep = new ModuleHotDependency(expr.range); dep.loc = expr.loc; parser.state.module.addDependency(dep); return true; }); }; compiler.hooks.compilation.tap( "HotModuleReplacementPlugin", (compilation, { normalModuleFactory }) => { // This applies the HMR plugin only to the targeted compiler // It should not affect child compilations if (compilation.compiler !== compiler) return; compilation.dependencyFactories.set( ModuleHotAcceptDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template() ); compilation.dependencyFactories.set( ModuleHotDeclineDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template() ); compilation.dependencyTemplates.set( ModuleHotDependency, new ModuleHotDependency.Template() ); compilation.hooks.record.tap( "HotModuleReplacementPlugin", (compilation, records) => { if (records.hash === compilation.hash) return; const chunkGraph = compilation.chunkGraph; records.hash = compilation.hash; records.moduleHashs = {}; for (const module of compilation.modules) { const identifier = module.identifier(); records.moduleHashs[identifier] = chunkGraph.getModuleHash( module ); } records.chunkHashs = {}; for (const chunk of compilation.chunks) { records.chunkHashs[chunk.id] = chunk.hash; } records.chunkModuleIds = {}; for (const chunk of compilation.chunks) { records.chunkModuleIds[ chunk.id ] = Array.from( chunkGraph.getOrderedChunkModulesIterable( chunk, compareModulesById(chunkGraph) ), m => chunkGraph.getModuleId(m) ); } } ); let initialPass = false; let recompilation = false; compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => { let records = compilation.records; if (!records) { initialPass = true; return; } if (!records.hash) initialPass = true; const preHash = records.preHash || "x"; const prePreHash = records.prePreHash || "x"; if (preHash === compilation.hash) { recompilation = true; compilation.modifyHash(prePreHash); return; } records.prePreHash = records.hash || "x"; records.preHash = compilation.hash; compilation.modifyHash(records.prePreHash); }); compilation.hooks.shouldGenerateChunkAssets.tap( "HotModuleReplacementPlugin", () => { if (multiStep && !recompilation && !initialPass) return false; } ); compilation.hooks.needAdditionalPass.tap( "HotModuleReplacementPlugin", () => { if (multiStep && !recompilation && !initialPass) return true; } ); compilation.hooks.processAssets.tap( { name: "HotModuleReplacementPlugin", stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL }, () => { const chunkGraph = compilation.chunkGraph; const records = compilation.records; if (records.hash === compilation.hash) return; if ( !records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds ) return; /** @type {Set<Module>} */ const updatedModules = new Set(); for (const module of compilation.modules) { const identifier = module.identifier(); const hash = chunkGraph.getModuleHash(module); if (records.moduleHashs[identifier] !== hash) { updatedModules.add(module); } } const hotUpdateMainContent = { c: [], r: [], m: undefined }; const allRemovedModules = new Set(); for (const key of Object.keys(records.chunkHashs)) { const currentChunk = find( compilation.chunks, chunk => `${chunk.id}` === key ); if (currentChunk) { const chunkId = currentChunk.id; const newModules = chunkGraph .getChunkModules(currentChunk) .filter(module => updatedModules.has(module)); const newRuntimeModules = Array.from( chunkGraph.getChunkRuntimeModulesIterable(currentChunk) ).filter(module => updatedModules.has(module)); const fullHashModules = chunkGraph.getChunkFullHashModulesIterable( currentChunk ); const newFullHashModules = fullHashModules && Array.from(fullHashModules).filter(module => updatedModules.has(module) ); /** @type {Set<number|string>} */ const allModules = new Set(); for (const module of chunkGraph.getChunkModulesIterable( currentChunk )) { allModules.add(chunkGraph.getModuleId(module)); } const removedModules = records.chunkModuleIds[chunkId].filter( id => !allModules.has(id) ); if (newModules.length > 0 || removedModules.length > 0) { const hotUpdateChunk = new HotUpdateChunk(); ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph); hotUpdateChunk.id = chunkId; chunkGraph.attachModules(hotUpdateChunk, newModules); chunkGraph.attachRuntimeModules( hotUpdateChunk, newRuntimeModules ); if (newFullHashModules) { chunkGraph.attachFullHashModules( hotUpdateChunk, newRuntimeModules ); } hotUpdateChunk.removedModules = removedModules; const renderManifest = compilation.getRenderManifest({ chunk: hotUpdateChunk, hash: records.hash, fullHash: records.hash, outputOptions: compilation.outputOptions, moduleTemplates: compilation.moduleTemplates, dependencyTemplates: compilation.dependencyTemplates, codeGenerationResults: compilation.codeGenerationResults, runtimeTemplate: compilation.runtimeTemplate, moduleGraph: compilation.moduleGraph, chunkGraph }); for (const entry of renderManifest) { const { path: filename, info: assetInfo } = compilation.getPathWithInfo( entry.filenameTemplate, entry.pathOptions ); const source = entry.render(); compilation.additionalChunkAssets.push(filename); compilation.emitAsset(filename, source, { hotModuleReplacement: true, ...assetInfo }); currentChunk.files.add(filename); compilation.hooks.chunkAsset.call(currentChunk, filename); } hotUpdateMainContent.c.push(chunkId); } } else { const chunkId = `${+key}` === key ? +key : key; hotUpdateMainContent.r.push(chunkId); for (const id of records.chunkModuleIds[chunkId]) allRemovedModules.add(id); } } hotUpdateMainContent.m = Array.from(allRemovedModules); const source = new RawSource(JSON.stringify(hotUpdateMainContent)); const { path: filename, info: assetInfo } = compilation.getPathWithInfo( compilation.outputOptions.hotUpdateMainFilename, { hash: records.hash } ); compilation.emitAsset(filename, source, { hotModuleReplacement: true, ...assetInfo }); } ); compilation.hooks.additionalTreeRuntimeRequirements.tap( "HotModuleReplacementPlugin", (chunk, runtimeRequirements) => { runtimeRequirements.add(RuntimeGlobals.hmrDownloadManifest); runtimeRequirements.add(RuntimeGlobals.hmrDownloadUpdateHandlers); runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution); runtimeRequirements.add(RuntimeGlobals.moduleCache); compilation.addRuntimeModule( chunk, new HotModuleReplacementRuntimeModule() ); } ); // TODO add HMR support for javascript/esm normalModuleFactory.hooks.parser .for("javascript/auto") .tap("HotModuleReplacementPlugin", addParserPlugins); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("HotModuleReplacementPlugin", addParserPlugins); NormalModule.getCompilationHooks(compilation).loader.tap( "HotModuleReplacementPlugin", context => { context.hot = true; } ); } ); } } module.exports = HotModuleReplacementPlugin;
function Controls() { let _matrix; let _stateManager; const THEMES = ['red-leds', 'yellow-leds', 'green-leds', 'blue-leds', 'white-leds', 'black-leds' ]; function init(stateManager, matrix) { _stateManager = stateManager; _matrix = matrix; $('#invert-button').click(_matrix.invert); $('#clear-button').click(_matrix.clear); $('#shift-up-button').click(_matrix.shiftUp); $('#shift-down-button').click(_matrix.shiftDown); $('#shift-left-button').click(_matrix.shiftLeft); $('#shift-right-button').click(_matrix.shiftRight); $('.leds-case').click(function () { setColor($(this).attr('id')); const themeName = THEMES.indexOf($(this).attr('id')); updateState({color: themeName}); }); $('#width-input').change(function () { _matrix.setup($('#width-input').val() | 0, $('#height-input').val() | 0); updateState({width: $('#width-input').val() | 0}); }); $('#height-input').change(function () { _matrix.setup($('#width-input').val() | 0, $('#height-input').val() | 0); updateState({height: $('#height-input').val() | 0}); }); } function setColor(color) { $('body').removeClass('red-leds yellow-leds green-leds blue-leds white-leds black-leds').addClass(color); } function stateChanged(state) { setColor(THEMES[state.color]); } function updateState(state) { _stateManager.updateState(state) } return { init: init, stateChanged: stateChanged, } }
// 模板使用页面 appController.controller('designDetailCtrl', ['$scope', '$rootScope', '$sce', '$stateParams', '$ionicLoading', '$ionicScrollDelegate', '$ionicPopover', '$ionicPopup', '$timeout', '$state', 'localStorageService', 'ShareService', 'IonicService', 'MsgBox', 'WechatApi', 'Con', function($scope, $rootScope, $sce, $stateParams, $ionicLoading, $ionicScrollDelegate, $ionicPopover, $ionicPopup, $timeout, $state, localStorageService, ShareService, IonicService, MsgBox, WechatApi, Con) { // $rootScope.menuShow = true; // $rootScope.backShow = true; // Con.log($stateParams); Con.log('首页详情'); // console.log($stateParams); // 用ifarme展示 // console.log(User); $scope.urlParams = JSON.parse($stateParams.itemPars); // console.log($scope.urlParams) // var url =$stateParams.puburl; // console.log(url); // iframe需要sce转化之后才可以打开 $scope.pubUrl = $sce.trustAsResourceUrl($scope.urlParams.puburl); $scope.storyTit = $scope.urlParams.title; $scope.templateId = $scope.urlParams.id; console.log($scope.urlParams) console.log('--------缩放-------') var win_w = angular.element(window)[0].innerWidth; var scaleValue = win_w / 320; console.log(scaleValue); jQuery('<meta id="mt-viewport" name="viewport" content="width=320, initial-scale=' + scaleValue + ', minimum-scale=' + scaleValue + ', maximum-scale=' + scaleValue + ', user-scalable=no" servergenerated="true">').appendTo('head'); $scope.createStoryByTemplateId = function(templateId) { // 注意有跨域问题 // console.log(jQuery(document.getElementById('iframeId').contentWindow.document)) // 修正预览平台app时候修改的外层viewport, 在离开当前预览页面的时候,把修改的viewport清除; if (jQuery('#mt-viewport').length > 0) { console.log('-----------移除viewport----------'); $rootScope.viewportRemoved = true; jQuery('#mt-viewport').remove(); jQuery('<meta name="viewport" content="width=320, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" servergenerated="true">').appendTo('head'); } var User = JSON.parse(localStorageService.get('User')); if (User) { User = JSON.parse(localStorageService.get('User')); var createStoryInfo = { templateID: templateId, userId: User.id, userToken: User.token, device: 'h5' } $ionicLoading.show({ content: 'Loading', animation: 'fade-in', showBackdrop: false, maxWidth: 200, showDelay: 0, duration: 10000 }); IonicService.createStoryByTemplateId(createStoryInfo).then(function(data) { $ionicLoading.hide(); if (data.status == 1 && data.message == 'success') { $state.go('tab.edit', { storyId: data.storyId }); } else { localStorageService.remove('User'); MsgBox.showTexts('未登录'); $rootScope.openLoginModal(); } }) } else { $timeout(function() { // 把当前连接保存,以便登陆后可以重新回到该地址 $rootScope.changeState = window.location.href; $rootScope.openLoginModal(); }, 100); } } }]);
export function buildTree(data) { let map = new Map() let items = [] for (let item of data) { item.children = [] map.set(item.id, item) } for (let [, item] of map) { if (item.parentId === 0) { items.push(item) } else { let parent = map.get(item.parentId) parent.children.push(item) } } return items }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.isObjEmpty = isObjEmpty; exports.cloneop = cloneop; exports.isObject = isObject; //判断是不是空对象 function isObjEmpty(obj) { return JSON.stringify(obj) == "{}"; } //对象类 //比较两个对象是否一样、 var diffObj = exports.diffObj = function diffObj(obj1, obj2) { return JSON.stringify(obj1) !== JSON.stringify(obj2); }; //深拷贝!!!!!,可以是对象也可以是数组 function cloneop(obj) { var copy = void 0; // Handle the 3 simple types, and null or undefined if (null == obj || 'object' != (typeof obj === "undefined" ? "undefined" : _typeof(obj))) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = cloneop(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = cloneop(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } //判断是否是对象 function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } //去除对象中指定的属性 var deleteObjKey = exports.deleteObjKey = function deleteObjKey() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var obj = arguments[1]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = arr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var i = _step.value; delete obj[i]; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return obj; };
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //----------------------------------------------------------------------------- var BUGNUMBER = 341939; var summary = 'Let block does not require semicolon'; var actual = ''; var expect = 'No Error'; printBugNumber(BUGNUMBER); printStatus (summary); try { eval('let (a) {} print(42);'); actual = 'No Error'; } catch(ex) { actual = ex + ''; } reportCompare(expect, actual, summary);
/** * @flow */ const ListRole: AXObjectModelDefinition = { relatedConcepts: [ { module: 'ARIA', concept: { name: 'list', }, }, { module: 'HTML', concept: { name: 'ul', }, }, { module: 'HTML', concept: { name: 'ol', }, }, ], type: 'structure', }; export default ListRole;
'use strict'; var parenthesize = function(input, list) { if (list === undefined) { return parenthesize(input, []); } else { var token = input.shift(); if (token === undefined) { return list.pop(); } else if (token === "(") { list.push(parenthesize(input, [])); return parenthesize(input, list); } else if (token === ")") { return list; } else { return parenthesize(input, list.concat(token)); } } }; var tokenize = function(input) { return input.split('"') .map(function(x, i) { if (i % 2 === 0) { // not in string return x.replace(/[\(\[\{]/g, ' ( ') .replace(/[\)\]\}]/g, ' ) ') .replace(/\|/g, ' ') .replace(/\,/g, ' '); } else { // in string return x.replace(/ /g, "!whitespace!"); } }) .join('"') .trim() .split(/\s+/) .map(function(x) { return x.replace(/!whitespace!/g, " "); }); }; var parse = function(input) { return Array.isArray(input) ? input : parenthesize(tokenize(input)); }; module.exports = parse;
import pkg from './package.json' import vuePlugin from 'rollup-plugin-vue' import scss from 'rollup-plugin-scss' import peerDepsExternal from 'rollup-plugin-peer-deps-external' import resolve from '@rollup/plugin-node-resolve' import commonjs from '@rollup/plugin-commonjs' import json from '@rollup/plugin-json' import replace from '@rollup/plugin-replace' import babel from '@rollup/plugin-babel' import ts from 'rollup-plugin-typescript2' import { terser } from 'rollup-plugin-terser' const name = 'Element3' const createBanner = () => { return `/*! * ${pkg.name} v${pkg.version} * (c) ${new Date().getFullYear()} kkb * @license MIT */` } const createBaseConfig = () => { return { input: 'src/index.js', external: ['vue'], plugins: [ peerDepsExternal(), vuePlugin({ css: true }), ts(), babel({ exclude: 'node_modules/**', extensions: ['.js', '.jsx', '.vue'], babelHelpers: 'bundled' }), resolve({ extensions: ['.vue', '.jsx', '.js'] }), commonjs(), json(), scss() ], output: { sourcemap: false, banner: createBanner(), externalLiveBindings: false, globals: { vue: 'Vue' } } } } function mergeConfig(baseConfig, configB) { const config = Object.assign({}, baseConfig) // plugin if (configB.plugins) { baseConfig.plugins.push(...configB.plugins) } // output config.output = Object.assign({}, baseConfig.output, configB.output) return config } function createFileName(formatName) { return `dist/element3-ui.${formatName}.js` } // es-bundle const esBundleConfig = { plugins: [ replace({ __DEV__: `(process.env.NODE_ENV !== 'production')` }) ], output: { file: createFileName('esm-bundler'), format: 'es' } } // es-browser const esBrowserConfig = { plugins: [ replace({ __DEV__: true }) ], output: { file: createFileName('esm-browser'), format: 'es' } } // es-browser.prod const esBrowserProdConfig = { plugins: [ terser(), replace({ __DEV__: false }) ], output: { file: createFileName('esm-browser.prod'), format: 'es' } } // cjs const cjsConfig = { plugins: [ replace({ __DEV__: true }) ], output: { file: createFileName('cjs'), format: 'cjs' } } // cjs.prod const cjsProdConfig = { plugins: [ terser(), replace({ __DEV__: false }) ], output: { file: createFileName('cjs.prod'), format: 'cjs' } } // global const globalConfig = { plugins: [ replace({ __DEV__: true, 'process.env.NODE_ENV': true }) ], output: { file: createFileName('global'), format: 'iife', name } } // global.prod const globalProdConfig = { plugins: [ terser(), replace({ __DEV__: false, 'process.env.NODE_ENV': true }) ], output: { file: createFileName('global.prod'), format: 'iife', name } } const prodFormatConfigs = [ esBundleConfig, esBrowserProdConfig, esBrowserConfig, cjsConfig, cjsProdConfig, globalConfig, globalProdConfig ] const devFormatConfigs = [esBundleConfig] function createPackageConfigs() { return getFormatConfigs().map((formatConfig) => { return mergeConfig(createBaseConfig(), formatConfig) }) } function getFormatConfigs() { return process.env.NODE_ENV === 'development' ? devFormatConfigs : prodFormatConfigs } export default createPackageConfigs()
{% load djblets_js reviewtags %} el: document.body, reviewRequestData: { bugTrackerURL: "{% if review_request.repository.bug_tracker %}{% url 'bug_url' review_request.display_id '--bug_id--' %}{% endif %}", id: {{review_request.display_id}}, localSitePrefix: "{% if review_request.local_site %}s/{{review_request.local_site.name}}/{% endif %}", branch: "{{review_request_details.branch|escapejs}}", bugsClosed: {{review_request_details.get_bug_list|json_dumps}}, {% if draft.changedesc %} changeDescription: "{{draft.changedesc.text|escapejs}}", {% endif %} description: "{{review_request_details.description|escapejs}}", hasDraft: {% if draft %}true{% else %}false{% endif %}, lastUpdatedTimestamp: {{review_request.last_updated|json_dumps}}, public: {% if review_request.public %}true{% else %}false{% endif %}, reviewURL: "{{review_request.get_absolute_url|escapejs}}", state: RB.ReviewRequest.{% if review_request.status == 'P' %}PENDING{% elif review_request.status == 'D' %}CLOSE_DISCARDED{% elif review_request.status == 'S' %}CLOSE_SUBMITTED{% endif %}, summary: "{{review_request_details.summary|escapejs}}", targetGroups: [{% spaceless %} {% for group in review_request_details.target_groups.all %} { name: "{{group.name|escapejs}}", url: "{{group.get_absolute_url}}" }{% if not forloop.last %},{% endif %} {% endfor %}{% endspaceless %}], targetPeople: [{% spaceless %} {% for user in review_request_details.target_people.all %} { username: "{{user.username|escapejs}}", url: "{{user.get_absolute_url}}" }{% if not forloop.last %},{% endif %} {% endfor %}{% endspaceless %}], testingDone: "{{review_request_details.testing_done|escapejs}}" }, editorData: { mutableByUser: {{mutable_by_user|yesno:'true,false'}}, statusMutableByUser: {{status_mutable_by_user|yesno:'true,false'}}, fileAttachmentComments: { {% if all_file_attachments %} {% for file_attachment in all_file_attachments %} {{file_attachment.id}}: {% file_attachment_comments file_attachment %}{% if not forloop.last %},{% endif %} {% endfor %} {% endif %} } }
jest.dontMock('../../components/shared/PageContainer.jsx'); jest.dontMock('classnames'); import React from 'react/addons'; import PageContainer from '../../components/shared/PageContainer.jsx'; const TestUtils = React.addons.TestUtils; function renderedOutput(elt) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(elt); return shallowRenderer.getRenderOutput(); } describe('<PageContainer />', () => { // let pageContainer, pageContainerRendered; let pageContainer; beforeEach(() => { const component = ( <PageContainer headline="I am headline" classNames="banana" > <p>The human torch was denied a bank loan.</p> </PageContainer> ); pageContainer = renderedOutput(component); // pageContainerRendered = TestUtils.renderIntoDocument(component); }); it('should have the correct tag', () => { expect(pageContainer.type).toBe('div'); }); it('should render all the children', () => { expect(pageContainer.props.children).toEqual([ <h2 className="PageContainer__headline">I am headline</h2>, <p>The human torch was denied a bank loan.</p> ]); }); // To do it('should have the correct class names', () => { expect(pageContainer.props.className).toEqual('page-content banana'); }); });
'use strict'; const axios = require('axios'); const chalk = require('chalk'); const pick = require('lodash.pick'); const prettyjson = require('prettyjson'); const store = require('./services/store'); const url = 'http://api.mongoosecloud.io/api'; const deploymentProps = [ 'organizationName', 'repoName', 'branch', 'createdAt', 'status', 'urls', 'mongodb' ]; module.exports = async function deployment(deploymentId) { const authorization = store.get('token'); if (!authorization) { console.log(chalk.red(`Must be logged in first, run "mongoose-cloud login"`)); process.exit(-1); } const opts = { headers: { authorization } }; const { deployment, logs } = await axios.get(`${url}/deployment/${deploymentId}`, opts). then(res => res.data); console.log(prettyjson.render({ ...pick(deployment, deploymentProps), logs })); };
/** * @author sunag / http://www.sunag.com.br/ */ import { Matrix4 } from '../../../../build/three.module.js'; import { InputNode } from '../core/InputNode.d.ts'; function Matrix4Node( matrix ) { InputNode.call( this, 'm4' ); this.value = matrix || new Matrix4(); } Matrix4Node.prototype = Object.create( InputNode.prototype ); Matrix4Node.prototype.constructor = Matrix4Node; Matrix4Node.prototype.nodeType = "Matrix4"; Object.defineProperties( Matrix4Node.prototype, { elements: { set: function ( val ) { this.value.elements = val; }, get: function () { return this.value.elements; } } } ); Matrix4Node.prototype.generateReadonly = function ( builder, output, uuid, type /*, ns, needsUpdate */ ) { return builder.format( "mat4( " + this.value.elements.join( ", " ) + " )", type, output ); }; Matrix4Node.prototype.copy = function ( source ) { InputNode.prototype.copy.call( this, source ); this.scope.value.fromArray( source.elements ); return this; }; Matrix4Node.prototype.toJSON = function ( meta ) { var data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); data.elements = this.value.elements.concat(); } return data; }; export { Matrix4Node };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Class representing a PetAPInPropertiesWithAPString. */ class PetAPInPropertiesWithAPString { /** * Create a PetAPInPropertiesWithAPString. * @property {number} id * @property {string} [name] * @property {boolean} [status] * @property {string} odatalocation * @property {object} [additionalProperties1] */ constructor() { } /** * Defines the metadata of PetAPInPropertiesWithAPString * * @returns {object} metadata of PetAPInPropertiesWithAPString * */ mapper() { return { required: false, serializedName: 'PetAPInPropertiesWithAPString', type: { name: 'Composite', additionalProperties: { type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, className: 'PetAPInPropertiesWithAPString', modelProperties: { id: { required: true, serializedName: 'id', type: { name: 'Number' } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, status: { required: false, readOnly: true, serializedName: 'status', type: { name: 'Boolean' } }, odatalocation: { required: true, serializedName: '@odata\\.location', type: { name: 'String' } }, additionalProperties1: { required: false, serializedName: 'additionalProperties', type: { name: 'Dictionary', value: { required: false, serializedName: 'NumberElementType', type: { name: 'Number' } } } } } } }; } } module.exports = PetAPInPropertiesWithAPString;
// This file was automatically generated from common.soy. // Please don't edit this file by hand. if (typeof apps == 'undefined') { var apps = {}; } apps.messages = function(opt_data, opt_ignored, opt_ijData) { return '<div style="display: none"><span id="subtitle">sjónrænt forritunarumhverfi</span><span id="blocklyMessage">Blockly</span><span id="codeTooltip">Sjá forritið sem JavaScript kóða.</span><span id="linkTooltip">Vista og tengja við kubba.</span><span id="runTooltip">Keyra forritið sem kubbarnir á vinnusvæðinu mynda.</span><span id="runProgram">Keyra forritið</span><span id="resetProgram">Byrja aftur</span><span id="dialogOk">Í lagi</span><span id="dialogCancel">Hætta við</span><span id="catLogic">Rökvísi</span><span id="catLoops">Lykkjur</span><span id="catMath">Reikningur</span><span id="catText">Texti</span><span id="catLists">Listar</span><span id="catColour">Litir</span><span id="catVariables">Breytur</span><span id="catProcedures">Stefjur</span><span id="httpRequestError">Það kom upp vandamál með beiðnina.</span><span id="linkAlert">Deildu kubbunum þínum með þessari krækju:</span><span id="hashError">Því miður, \'%1\' passar ekki við neitt vistað forrit.</span><span id="xmlError">Gat ekki hlaðið vistuðu skrána þína. Var hún kannske búin til í annarri útgáfu af Blockly?</span><span id="listVariable">listi</span><span id="textVariable">texti</span></div>'; }; apps.dialog = function(opt_data, opt_ignored, opt_ijData) { return '<div id="dialogShadow" class="dialogAnimate"></div><div id="dialogBorder"></div><div id="dialog"></div>'; }; apps.codeDialog = function(opt_data, opt_ignored, opt_ijData) { return '<div id="dialogCode" class="dialogHiddenContent"><pre id="containerCode"></pre>' + apps.ok(null, null, opt_ijData) + '</div>'; }; apps.storageDialog = function(opt_data, opt_ignored, opt_ijData) { return '<div id="dialogStorage" class="dialogHiddenContent"><div id="containerStorage"></div>' + apps.ok(null, null, opt_ijData) + '</div>'; }; apps.ok = function(opt_data, opt_ignored, opt_ijData) { return '<div class="farSide" style="padding: 1ex 3ex 0"><button class="secondary" onclick="BlocklyApps.hideDialog(true)">Í lagi</button></div>'; }; ; // This file was automatically generated from template.soy. // Please don't edit this file by hand. if (typeof graphpage == 'undefined') { var graphpage = {}; } graphpage.messages = function(opt_data, opt_ignored, opt_ijData) { return apps.messages(null, null, opt_ijData); }; graphpage.start = function(opt_data, opt_ignored, opt_ijData) { return graphpage.messages(null, null, opt_ijData) + '<table width="100%"><tr><td><h1><span id="title"><a href="../index.html?lang=' + soy.$$escapeHtml(opt_ijData.lang) + '">Blockly</a> : Reiknir með línuriti</span></h1></td><td class="farSide"><select id="languageMenu"></select>&nbsp; &nbsp;<button id="linkButton" class="notext" title="Vista og tengja við kubba."><img src=\'link.png\' height=21 width=21></button></div></td></tr></table><div id="visualization"></div><div id="funcText"><img id="y1" src="../../media/1x1.gif">...</div><script type="text/javascript" src="../../blockly_compressed.js"><\/script><script type="text/javascript" src="../../blocks_compressed.js"><\/script><script type="text/javascript" src="../../javascript_compressed.js"><\/script><script type="text/javascript" src="../../' + soy.$$escapeHtml(opt_ijData.langSrc) + '"><\/script><script type="text/javascript" src="blocks.js"><\/script>' + graphpage.toolbox(null, null, opt_ijData) + '<div id="blockly"></div>' + apps.dialog(null, null, opt_ijData) + apps.storageDialog(null, null, opt_ijData); }; graphpage.toolbox = function(opt_data, opt_ignored, opt_ijData) { return '<xml id="toolbox" style="display: none"><category name="Reikningur"><block type="math_number"></block><block type="math_arithmetic"></block><block type="math_single"></block><block type="math_trig"></block><block type="math_constant"></block><block type="math_number_property"></block><block type="math_round"></block><block type="math_modulo"></block><block type="math_constrain"><value name="LOW"><block type="math_number"><title name="NUM">1</title></block></value><value name="HIGH"><block type="math_number"><title name="NUM">100</title></block></value></block><block type="math_random_int"><value name="FROM"><block type="math_number"><title name="NUM">1</title></block></value><value name="TO"><block type="math_number"><title name="NUM">100</title></block></value></block><block type="math_random_float"></block></category><category name="Breytur"><block type="graph_get_x"></block></category><category name="Rökvísi"><block type="logic_compare"></block><block type="logic_operation"></block><block type="logic_negate"></block><block type="logic_boolean"></block><block type="logic_ternary"></block></category></xml>'; };
class Category { } // currently only shared by Weekly and Collection class BaseCollection extends Category { currentMarkers() { return [].concat(...this.items.map(item => item.currentMarkers())); } // “Sell” event handler shared by Weekly and Collection to be found in Collection. // And this comment is shorter than the overhead for splitting that handler. } class Weekly extends BaseCollection { static init() { this.allSets = {}; const allWeeklySets = Loader.promises['weekly_sets'].consumeJson(({ sets }) => { this.allSets.sets = sets; }); const currentSet = Loader.promises['weekly'].consumeJson(data => { this.allSets.current = data.set.replace(/AWARD_ROLE_COLLECTOR_SET_/, '').toLowerCase() + '_set'; }); return Promise.all([allWeeklySets, currentSet]) .then(() => { this.current = new Weekly(this.allSets); this._installSettingsAndEventHandlers(); console.info('%c[Weekly Set] Loaded!', 'color: #bada55; background: #242424'); }) .catch(() => { console.info('%c[Weekly Set] Unable to load!', 'color: #FF6969; background: #242424'); }); } // needs Item.items ready constructor(data) { super(); const nameViaParam = getParameterByName('weekly'); this.weeklyId = data.sets[nameViaParam] ? nameViaParam : data.current; this.weeklySetValue = data.sets[this.weeklyId].value; this.items = data.sets[this.weeklyId].items.map(itemId => Item.items.find(i => i.itemId === itemId) || new NonCollectible({ itemId })); this.collectibleItems = this.items.filter(item => item.constructor === Item); this._insertMenuElements(); } _insertMenuElements() { this.$menuEntry = $(` <div id="weekly-container"> <div class="header"> <span class="header-border"></span> <h2 class="header-title weekly-item-title" data-text="weekly.desc.${this.weeklyId}"> Weekly Collection</h2> <span class="header-border"></span> </div> <div class="weekly-item-listings"> <p> <span class="weekly-flavor-text" data-text="weekly.flavor.${this.weeklyId}"></span> <span data-text="menu.weekly_item_description">Find all the items listed and sell the complete collection to Madam Nazar for an XP and RDO$ reward.</span> </p> <div class="collection-value"> <span class="weekly-set-value" data-help="item_value">$${this.weeklySetValue.toFixed(2)}</span> <span class="collection-sell" data-text="menu.sell" data-help="item_sell">Sell</span> </div> </div> </div> `) .translate() .insertBefore('.links-container'); this.$menuEntry[0].rdoCollection = this; this.$listParent = this.$menuEntry.find('.weekly-item-listings'); this.items.forEach(item => item._insertWeeklyMenuElement(this.$listParent)); Loader.mapModelLoaded.then(() => { SettingProxy.addListener(InventorySettings, 'isEnabled', () => this.$menuEntry .find('.collection-value') .toggle(InventorySettings.isEnabled || this.weeklySetValue !== 0) .end() .find('.collection-sell') .toggle(InventorySettings.isEnabled) .end() .find('.weekly-set-value') .toggle(this.weeklySetValue !== 0) .end() )(); }); } static _installSettingsAndEventHandlers() { SettingProxy.addSetting(Settings, 'showWeeklySettings', { default: true }); const weeklyCheckbox = $("#show-weekly"); Loader.mapModelLoaded.then(() => { SettingProxy.addListener(Settings, 'showWeeklySettings', () => { this.current.$menuEntry.toggleClass('opened', Settings.showWeeklySettings); weeklyCheckbox.prop('checked', Settings.showWeeklySettings); })(); weeklyCheckbox.on("change", () => { Settings.showWeeklySettings = weeklyCheckbox.prop('checked'); MapBase.addMarkers(); }) }); } } class Collection extends BaseCollection { constructor(preliminary) { super(); Object.assign(this, preliminary); this.items = []; // filled by new Item()s this._insertMenuElement(); } static init(collections) { this._installSettingsAndEventHandlers(); this.collections = []; collections.forEach(interim => this.collections.push(new Collection(interim))); } static updateMenu() { this.collections.forEach(collection => collection.updateMenu()); } static switchCycle(categoriesArray, cycle) { categoriesArray.forEach(category => { $(`.input-cycle[name=${category}]`).val(cycle); Cycles.categories[category] = cycle; }); } static _installSettingsAndEventHandlers() { SettingProxy.addSetting(Settings, 'sortItemsAlphabetically', { default: false }); Loader.mapModelLoaded.then(() => { const checkbox = $('#sort-items-alphabetically') .prop("checked", Settings.sortItemsAlphabetically) .on("change", () => Settings.sortItemsAlphabetically = checkbox.prop('checked')); SettingProxy.addListener(Settings, 'sortItemsAlphabetically language', () => Collection.collections.forEach(collection => collection.menuSort(Settings.sortItemsAlphabetically)))(); $('.side-menu') .on('change', event => { const $input = $(event.target); const collection = $input.propSearchUp('rdoCollection'); if (collection && $input.hasClass('input-cycle')) { event.stopImmediatePropagation(); switch (collection.category) { case 'cups': case 'swords': case 'wands': case 'pentacles': this.switchCycle(['cups', 'swords', 'wands', 'pentacles'], +$input.val()); break; case 'bracelet': case 'earring': case 'necklace': case 'ring': this.switchCycle(['bracelet', 'earring', 'necklace', 'ring', 'jewelry_random'], +$input.val()); break; case 'coastal': case 'oceanic': case 'megafauna': this.switchCycle(['coastal', 'oceanic', 'megafauna', 'fossils_random'], +$input.val()); break; default: this.switchCycle([collection.category], +$input.val()); break; } MapBase.addMarkers(); Menu.refreshMenu(); } // on capture phase to override more generic handler in scripts.js })[0].addEventListener('click', event => { const etcL = event.target.classList; if (etcL.contains('input-cycle')) { // handled by browser _alone_: avoid own category enabled/disabled handler } else if (etcL.contains('collection-sell') || etcL.contains('collection-collect-all')) { const collection = $(event.target).propSearchUp('rdoCollection'); const changeAmount = etcL.contains('collection-sell') ? -1 : 1; collection.items.forEach(i => i.changeAmountWithSideEffects(changeAmount)); collection.currentMarkers().forEach(marker => { if (InventorySettings.autoEnableSoldItems && marker.item.amount === 0 && marker.isCollected) { MapBase.removeItemFromMap(marker.cycleName, marker.text, marker.subdata, marker.category, false); } }); } else if (etcL.contains('collection-reset')) { const collection = $(event.target).propSearchUp('rdoCollection'); collection.currentMarkers().filter(marker => !marker.canCollect).forEach(marker => { MapBase.removeItemFromMap(marker.cycleName, marker.text, marker.subdata, marker.category, true); }); } else if (etcL.contains('disable-collected-items')) { const collection = $(event.target).propSearchUp('rdoCollection'); collection.currentMarkers() .filter(marker => marker.canCollect && marker.item.amount > 0) .forEach(marker => { $(`[data-type=${marker.legacyItemId}] .collectible-text p`).addClass('disabled'); MapBase.removeItemFromMap(marker.cycleName, marker.text, marker.subdata, marker.category, true); }); } else { return; // event not for “us” } event.stopImmediatePropagation(); }, { capture: true }); }); } _insertMenuElement() { const $element = $(` <div> <div class="menu-option clickable" data-type="${this.category}" data-help="item_category"> <span> <img class="icon" src="assets/images/icons/${this.category}.png" alt="${this.category}"> <span> <span class="menu-option-text" data-text="menu.${this.category}"></span> <img class="same-cycle-warning-menu" src="assets/images/same-cycle-alert.png"> </span> </span> <input class="input-text input-cycle hidden" type="number" min="1" max="6" name="${this.category}" data-help="item_manual_cycle"> <img class="cycle-icon hidden" src="assets/images/cycle_1.png" alt="Cycle 1" data-type="${this.category}"> <div class="open-submenu"></div> </div> <div class="menu-hidden" data-type="${this.category}"> <div class="collection-value"> <span class="collection-collected" data-help="collection_collected"></span> <span data-help="item_value">$${this.price.toFixed(2)}</span> <span class="collection-reset" data-text="menu.reset" data-help="item_reset">Reset</span> <span class="collection-sell" data-text="menu.sell" data-help="item_sell">Sell</span> </div> <div class="collection-value-bottom"> <span class="disable-collected-items" data-text="menu.disable_collected_items" data-help="disable_collected_items">Disable collected</span> <span class="collection-collect-all" data-text="menu.collection_collect_all" data-help="collection_collect_all">Collect all</span> </div> </div> </div> `).translate() .find('.input-cycle, .cycle-icon').addClass('hidden').end() // improve visuals during initial loading .insertBefore('#collection-insertion-before-point'); $element[0].rdoCollection = this; [this.$menuButton, this.$submenu] = $element.children().toArray().map(e => $(e)); this.$menuButton.find('.same-cycle-warning-menu').hide().end(); Loader.mapModelLoaded.then(() => { SettingProxy.addListener(Settings, 'isCycleInputEnabled', () => this.$menuButton .find('.input-cycle').toggleClass('hidden', !Settings.isCycleInputEnabled).end() .find('.cycle-icon').toggleClass('hidden', !Settings.isCyclesVisible || Settings.isCycleInputEnabled).end() )(); SettingProxy.addListener(InventorySettings, 'isEnabled enableAdvancedInventoryOptions', () => this.$submenu .find('.collection-sell').toggle(InventorySettings.isEnabled).end() .find('.collection-value-bottom').toggle(InventorySettings.isEnabled && InventorySettings.enableAdvancedInventoryOptions).end() )(); }); } updateMenu() { const categoryItems = this.items.map(item => item.updateMenu()); const containsBuggedItems = categoryItems.some(item => item.isBugged); const containsRandomItems = categoryItems.some(item => item.isRandom); const isSameCycle = Cycles.isSameAsYesterday(this.category); this.$menuButton .attr('data-help', () => { if (isSameCycle) { return 'item_category_same_cycle'; } else if (containsBuggedItems && containsRandomItems) { return 'item_category_unavailable_items'; } else if (containsBuggedItems) { return 'item_category_bugged_items'; } else if (containsRandomItems) { return 'item_category_random_items'; } else { return 'item_category'; } }) .toggleClass('random-category', containsRandomItems) .toggleClass('not-found', containsBuggedItems) .find('.same-cycle-warning-menu') .toggle(isSameCycle) .end(); this.updateCounter(); } updateCounter() { this.$submenu .find('.collection-collected') .text(Language.get('menu.collection_counter') .replace('{count}', this.$submenu.find('.disabled').length) .replace('{max}', this.items.length) ); } menuSort(alphabetically) { if (['cups', 'swords', 'wands', 'pentacles'].includes(this.category)) return; const items = !alphabetically ? this.items : [...this.items].sort((...args) => { const [a, b] = args.map(item => Language.get(item.itemTranslationKey)); return a.localeCompare(b, Settings.language, { sensitivity: 'base' }); }); this.$submenu.append(items.map(item => item.$menuButton)); } averageAmount() { return this.items.reduce((sum, item) => sum + item.amount, 0) / this.items.length; } effectiveAmount() { return Math.min(...this.items.map(item => item.effectiveAmount())); } totalValue() { const collectionAmount = this.effectiveAmount(); return this.items .map(item => (item.effectiveAmount() - collectionAmount) * item.price) .reduce((a, b) => a + b, 0) + collectionAmount * this.price; } static totalValue() { return this.collections.reduce((sum, collection) => sum + collection.totalValue(), 0); } }
const express = require("express"); const router = express.Router(); // Import modules from other file const { adminValidation } = require("./middleware/verification"); const { createNewAccount, createAccountInformation, getAllRolesInformation, getAccountsByRole, createNewGuestAccount, updateGuestAccount, updateGuestAccountStatus, updateAccountStatus, getAllGuestAccounts, deleteGuestAccountById, deleteAccountById, } = require("../utils/dbService/index"); /** * @method GET * @api /api/admin/roles/ * @description API route to get all roles * @params null * @return * - status: Int, * - success: Boolean * - roles: Array[] */ router.get("/roles", adminValidation, async (req, res) => { // Get all roles information from database const query = getAllRolesInformation(); await query .then((result) => { res.status(200).json({ status: res.statusCode, success: true, roles: result, }); }) .catch((err) => { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }); /** * @method GET * @API /api/admin/accounts/:roleId/ * @description API route to get all accounts by role * @params * - roleId: Int * @return * - status: Int * - success: Boolean * - accounts: Array[] */ router.get("/accounts/:roleId", adminValidation, async (req, res) => { // Get accountId from params const { roleId } = req.params; // Get all accounts of roleId const query = getAccountsByRole(roleId); await query .then((result) => { res.status(200).json({ status: res.statusCode, success: true, accounts: result, }); }) .catch((err) => { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }); /** * @method GET * @API /api/admin/guest-accounts/ * @description API route to get all guest accounts * @params * @return * - status: Int * - success: Boolean * - guestAccounts: Array[] */ router.get("/guest-accounts", adminValidation, async (req, res) => { // Get all accounts of roleId const query = getAllGuestAccounts(); await query .then((result) => { res.status(200).json({ status: res.statusCode, success: true, guestAccounts: result, }); }) .catch((err) => { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }); /** * @method POST * @API /api/admin/accounts/ * @description API route to create new internal account * @params * - email: String * - firstName: String * - surName: String * - roleId: Int * - facultyId: Int * @return */ router.post("/accounts", adminValidation, async (req, res) => { const { email, firstName, surName, roleId, facultyId } = req.body; // Create account info Object const accountInfo = { email: email, roleId: roleId, facultyId: facultyId, }; // Create new user account in database const query = createNewAccount(accountInfo); await query .then(async (result) => { // If account created successful, create acocunt detail Object const accountDetail = { firstName: firstName, surName: surName, }; // Create user information const query1 = createAccountInformation(accountDetail, result.insertId); await query1 .then((result1) => { return res.status(200).json({ status: res.statusCode, success: true, message: "Account created successfully", }); }) .catch((err) => { console.log("Err: ", err); return res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }) .catch((err) => { console.log("Err: ", err); return res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }); /** * @method POST * @API /api/admin/guest-accounts/ * @description API route to create new guest account * @params * - username: String * - password: String * - facultyId: Int * @return * - status: Int * - success: Boolean * - message: String */ router.post("/guest-accounts", adminValidation, async (req, res) => { // Get data from req.body const { username, password, facultyId } = req.body; // Create guest account info Object const guestAccountInfo = { username: username, password: password, facultyId: facultyId, }; // Create new guest account in database const query = createNewGuestAccount(guestAccountInfo); await query .then((result) => { // If guest account inserted into database successful res.status(200).json({ status: res.statusCode, success: true, message: "Guest acccount created successfully", }); }) .catch((err) => { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }); /** * @method PATCH * @API /api/admin/accounts/:accountId/ * @description API route to update account status (enable/disable) * @params * - accountId: Int * - status: Int * @return * - status: Int * - success: Boolean * - message: String */ router.patch("/accounts/:accountId", adminValidation, async (req, res) => { // Get accountId from params const { accountId } = req.params; // Get status from req.body const { status } = req.body; // Update guest account const query = updateAccountStatus(status, accountId); await query .then((result) => { res.status(200).json({ status: res.statusCode, success: true, message: `Account ${status ? "unactivated" : "activated"} successfully`, }); }) .catch((err) => { if (!!err) { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); } else { res.status(404).json({ status: res.statusCode, success: false, message: "Not found", }); } }); }); /** * @method PATCH * @API /api/admin/guest-accounts/:accountId/ * @description API route to update guest account status (enable/disable) * @params * - accountId: Int * - status: Int * @return * - status: Int * - success: Boolean * - message: String */ router.patch( "/guest-accounts/:accountId", adminValidation, async (req, res) => { // Get accountId from params const { accountId } = req.params; // Get status from req.body const { status } = req.body; // Update guest account const query = updateGuestAccountStatus(status, accountId); await query .then((result) => { return res.status(200).json({ status: res.statusCode, success: true, message: `Guest account ${ status ? "unactivated" : "activated" } successfully`, }); }) .catch((err) => { if (!!err) { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); } else { res.status(404).json({ status: res.statusCode, success: false, message: "Not found", }); } }); } ); /** * @method PUT * @API /api/admin/guest-accounts/:accountId/ * @description API route to update guest account information * @params * - username: String * - password: String * @return * - status: Int * - success: Boolean * - message: String */ router.put("/guest-accounts/:accountId", adminValidation, async (req, res) => { // Get accountId from params const { accountId } = req.params; // Get data from req.body const { username, password } = req.body; // Create Object to store guest account information const guestAccountInfo = { username: username, password: password, }; // Update guest account const query = updateGuestAccount(guestAccountInfo, accountId); await query .then((result) => { res.status(200).json({ status: res.statusCode, success: true, message: "Guest account updated successfully", }); }) .catch((err) => { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); }); }); /** * @method DELETE * @API /api/admin/accounts/:accountId/ * @description API route to delete account * @params * - accountId: Int * @return * - status: Int * - success: Boolean * - message: String */ router.delete("/accounts/:accountId", adminValidation, async (req, res) => { // Get accountId from params const { accountId } = req.params; // Update guest account const query = deleteAccountById(accountId); await query .then((result) => { return res.status(200).json({ status: res.statusCode, success: true, message: "Account deleted successful", }); }) .catch((err) => { if (!!err) { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); } else { res.status(404).json({ status: res.statusCode, success: false, message: "Not found", }); } }); }); /** * @method DELETE * @API /api/admin/guest-accounts/:accountId/ * @description API route to delete guest account * @params * - accountId: Int * @return * - status: Int * - success: Boolean * - message: String */ router.delete( "/guest-accounts/:accountId", adminValidation, async (req, res) => { // Get accountId from params const { accountId } = req.params; // Update guest account const query = deleteGuestAccountById(accountId); await query .then((result) => { return res.status(200).json({ status: res.statusCode, success: true, message: "Guest account deleted successful", }); }) .catch((err) => { if (!!err) { console.log("Err: ", err); res.status(501).json({ status: res.statusCode, success: false, message: "Bad request", }); } else { res.status(404).json({ status: res.statusCode, success: false, message: "Not found", }); } }); } ); module.exports = router;
"use strict"; // tslint:disable /** * MailSlurp API * MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository * * OpenAPI spec version: 94bf4c59616d8bdb796bb55c6a0ad0cb4e00ccd3 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(require("./api"), exports); __exportStar(require("./configuration"), exports);
const path = require('path') require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` }) module.exports = { siteMetadata: { title: `Gatsby Shopify Starter`, description: `Kick off your next, ecommerce experience with this Gatsby starter. This starter ships with credentials to a shopify demo store so you can try it out immediately.`, author: `@alexanderhorl`, }, plugins: [ `gatsby-plugin-react-helmet`, `gatsby-plugin-sass`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, `gatsby-plugin-layout`, { resolve: `gatsby-plugin-google-fonts`, options: { fonts: [ `limelight`, `source sans pro\:300,400,400i,700`, // you can also specify font weights and styles 'UnifrakturMaguntia', ], display: 'swap' }, }, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, { resolve: `gatsby-source-shopify`, options: { // The domain name of your Shopify shop. This is required. // Example: 'gatsby-source-shopify-test-shop' if your Shopify address is // 'gatsby-source-shopify-test-shop.myshopify.com'. shopName: process.env.SHOP_NAME, // An API access token to your Shopify shop. This is required. // You can generate an access token in the "Manage private apps" section // of your shop's Apps settings. In the Storefront API section, be sure // to select "Allow this app to access your storefront data using the // Storefront API". // See: https://help.shopify.com/api/custom-storefronts/storefront-api/getting-started#authentication accessToken: process.env.SHOPIFY_ACCESS_TOKEN, // Set verbose to true to display a verbose output on `npm run develop` // or `npm run build`. This prints which nodes are being fetched and how // much time was required to fetch and process the data. // Defaults to true. verbose: true, }, }, { resolve: 'gatsby-plugin-root-import', options: { '~': path.join(__dirname, 'src/'), }, }, { resolve: `gatsby-plugin-offline`, options: { precachePages: [`/product/*`, `/collection/*`, `/`], }, }, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: "UA-134421805-1", anonymize: true, respectDNT: true, }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.app/offline // 'gatsby-plugin-offline', ], }
(window.webpackJsonp=window.webpackJsonp||[]).push([[253],{321:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return o})),n.d(t,"metadata",(function(){return c})),n.d(t,"toc",(function(){return s})),n.d(t,"default",(function(){return u}));var r=n(3),i=n(8),a=(n(0),n(553)),o={id:"high-availability-ha",title:"High Availability"},c={unversionedId:"guides/high-availability-ha",id:"version-v0.2/guides/high-availability-ha",isDocsHomePage:!1,title:"High Availability",description:"ORY Kratos does not have any special requirements when it comes to High",source:"@site/versioned_docs/version-v0.2/guides/high-availability-ha.md",sourceDirName:"guides",slug:"/guides/high-availability-ha",permalink:"/kratos/docs/v0.2/guides/high-availability-ha",editUrl:"https://github.com/ory/kratos/edit/master/docs/versioned_docs/version-v0.2/guides/high-availability-ha.md",version:"v0.2",lastUpdatedBy:"aeneasr",lastUpdatedAt:1588605498,formattedLastUpdatedAt:"5/4/2020",frontMatter:{id:"high-availability-ha",title:"High Availability"},sidebar:"version-v0.2/docs",previous:{title:"Multitenancy",permalink:"/kratos/docs/v0.2/guides/multi-tenancy-multitenant"},next:{title:"Configuration",permalink:"/kratos/docs/v0.2/reference/configuration"}},s=[],l={toc:s};function u(e){var t=e.components,n=Object(i.a)(e,["components"]);return Object(a.b)("wrapper",Object(r.a)({},l,n,{components:t,mdxType:"MDXLayout"}),Object(a.b)("p",null,"ORY Kratos does not have any special requirements when it comes to High\nAvailability as it does not manage state itself but instead relies on the SQL\ndatabase for that."),Object(a.b)("p",null,"It is therefore possible to use ORY Kratos with Auto-Scaling Groups (e.g. in\nKubernetes) without any additional configuration."))}u.isMDXComponent=!0},553:function(e,t,n){"use strict";n.d(t,"a",(function(){return p})),n.d(t,"b",(function(){return y}));var r=n(0),i=n.n(r);function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var l=i.a.createContext({}),u=function(e){var t=i.a.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):c(c({},t),e)),n},p=function(e){var t=u(e.components);return i.a.createElement(l.Provider,{value:t},e.children)},d={inlineCode:"code",wrapper:function(e){var t=e.children;return i.a.createElement(i.a.Fragment,{},t)}},f=i.a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,a=e.originalType,o=e.parentName,l=s(e,["components","mdxType","originalType","parentName"]),p=u(n),f=r,y=p["".concat(o,".").concat(f)]||p[f]||d[f]||a;return n?i.a.createElement(y,c(c({ref:t},l),{},{components:n})):i.a.createElement(y,c({ref:t},l))}));function y(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var a=n.length,o=new Array(a);o[0]=f;var c={};for(var s in t)hasOwnProperty.call(t,s)&&(c[s]=t[s]);c.originalType=e,c.mdxType="string"==typeof e?e:r,o[1]=c;for(var l=2;l<a;l++)o[l]=n[l];return i.a.createElement.apply(null,o)}return i.a.createElement.apply(null,n)}f.displayName="MDXCreateElement"}}]);
;var VueDemi = (function (VueDemi, Vue, VueCompositionAPI) { if (VueDemi.install) { return VueDemi } if (Vue) { if (Vue.version.slice(0, 2) === '2.') { if (VueCompositionAPI) { for (var key in VueCompositionAPI) { VueDemi[key] = VueCompositionAPI[key] } VueDemi.isVue2 = true VueDemi.isVue3 = false VueDemi.install = function (){} VueDemi.Vue = Vue VueDemi.Vue2 = Vue VueDemi.version = Vue.version } else { console.error( '[vue-demi] no VueCompositionAPI instance found, please be sure to import `@vue/composition-api` before `vue-demi`.' ) } } else if (Vue.version.slice(0, 2) === '3.') { for (var key in Vue) { VueDemi[key] = Vue[key] } VueDemi.isVue2 = false VueDemi.isVue3 = true VueDemi.install = function (){} VueDemi.Vue = Vue VueDemi.Vue2 = undefined VueDemi.version = Vue.version VueDemi.set = function(target, key, val) { if (Array.isArray(target)) { target.length = Math.max(target.length, key) target.splice(key, 1, val) return val } target[key] = val return val } VueDemi.del = function(target, key) { if (Array.isArray(target)) { target.splice(key, 1) return } delete target[key] } } else { console.error('[vue-demi] Vue version ' + Vue.version + ' is unsupported.') } } else { console.error( '[vue-demi] no Vue instance found, please be sure to import `vue` before `vue-demi`.' ) } return VueDemi })( this.VueDemi = this.VueDemi || (typeof VueDemi !== "undefined" ? VueDemi : {}), this.Vue || (typeof Vue !== "undefined" ? Vue : undefined), this.VueCompositionAPI || (typeof VueCompositionAPI !== "undefined" ? VueCompositionAPI : undefined) ); ; ;(function (exports, shared, vueDemi, core) { 'use strict'; function computedAsync(evaluationCallback, initialState, optionsOrRef) { let options; if (vueDemi.isRef(optionsOrRef)) { options = { evaluating: optionsOrRef }; } else { options = optionsOrRef || {}; } const { lazy = false, evaluating = void 0, onError = shared.noop } = options; const started = vueDemi.ref(!lazy); const current = vueDemi.ref(initialState); let counter = 0; vueDemi.watchEffect(async (onInvalidate) => { if (!started.value) return; counter++; const counterAtBeginning = counter; let hasFinished = false; if (evaluating) { Promise.resolve().then(() => { evaluating.value = true; }); } try { const result = await evaluationCallback((cancelCallback) => { onInvalidate(() => { if (evaluating) evaluating.value = false; if (!hasFinished) cancelCallback(); }); }); if (counterAtBeginning === counter) current.value = result; } catch (e) { onError(e); } finally { if (evaluating) evaluating.value = false; hasFinished = true; } }); if (lazy) { return vueDemi.computed(() => { started.value = true; return current.value; }); } else { return current; } } function computedInject(key, options, defaultSource, treatDefaultAsFactory) { let source = vueDemi.inject(key); if (defaultSource) source = vueDemi.inject(key, defaultSource); if (treatDefaultAsFactory) source = vueDemi.inject(key, defaultSource, treatDefaultAsFactory); if (typeof options === "function") { return vueDemi.computed((ctx) => options(source, ctx)); } else { return vueDemi.computed({ get: (ctx) => options.get(source, ctx), set: options.set }); } } const createUnrefFn = (fn) => { return function(...args) { return fn.apply(this, args.map((i) => vueDemi.unref(i))); }; }; function unrefElement(elRef) { var _a; const plain = vueDemi.unref(elRef); return (_a = plain == null ? void 0 : plain.$el) != null ? _a : plain; } const defaultWindow = shared.isClient ? window : void 0; const defaultDocument = shared.isClient ? window.document : void 0; const defaultNavigator = shared.isClient ? window.navigator : void 0; const defaultLocation = shared.isClient ? window.location : void 0; function useEventListener(...args) { let target; let event; let listener; let options; if (shared.isString(args[0])) { [event, listener, options] = args; target = defaultWindow; } else { [target, event, listener, options] = args; } if (!target) return shared.noop; let cleanup = shared.noop; const stopWatch = vueDemi.watch(() => unrefElement(target), (el) => { cleanup(); if (!el) return; el.addEventListener(event, listener, options); cleanup = () => { el.removeEventListener(event, listener, options); cleanup = shared.noop; }; }, { immediate: true, flush: "post" }); const stop = () => { stopWatch(); cleanup(); }; shared.tryOnScopeDispose(stop); return stop; } function onClickOutside(target, handler, options = {}) { const { window = defaultWindow, ignore, capture = true } = options; if (!window) return; const shouldListen = vueDemi.ref(true); const listener = (event) => { const el = unrefElement(target); const composedPath = event.composedPath(); if (!el || el === event.target || composedPath.includes(el) || !shouldListen.value) return; if (ignore && ignore.length > 0) { if (ignore.some((target2) => { const el2 = unrefElement(target2); return el2 && (event.target === el2 || composedPath.includes(el2)); })) return; } handler(event); }; const cleanup = [ useEventListener(window, "click", listener, { passive: true, capture }), useEventListener(window, "pointerdown", (e) => { const el = unrefElement(target); shouldListen.value = !!el && !e.composedPath().includes(el); }, { passive: true }) ]; const stop = () => cleanup.forEach((fn) => fn()); return stop; } var __defProp$h = Object.defineProperty; var __defProps$8 = Object.defineProperties; var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$j = Object.getOwnPropertySymbols; var __hasOwnProp$j = Object.prototype.hasOwnProperty; var __propIsEnum$j = Object.prototype.propertyIsEnumerable; var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$h = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$j.call(b, prop)) __defNormalProp$h(a, prop, b[prop]); if (__getOwnPropSymbols$j) for (var prop of __getOwnPropSymbols$j(b)) { if (__propIsEnum$j.call(b, prop)) __defNormalProp$h(a, prop, b[prop]); } return a; }; var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b)); const createKeyPredicate = (keyFilter) => { if (typeof keyFilter === "function") return keyFilter; else if (typeof keyFilter === "string") return (event) => event.key === keyFilter; else if (Array.isArray(keyFilter)) return (event) => keyFilter.includes(event.key); else if (keyFilter) return () => true; else return () => false; }; function onKeyStroke(key, handler, options = {}) { const { target = defaultWindow, eventName = "keydown", passive = false } = options; const predicate = createKeyPredicate(key); const listener = (e) => { if (predicate(e)) handler(e); }; return useEventListener(target, eventName, listener, passive); } function onKeyDown(key, handler, options = {}) { return onKeyStroke(key, handler, __spreadProps$8(__spreadValues$h({}, options), { eventName: "keydown" })); } function onKeyPressed(key, handler, options = {}) { return onKeyStroke(key, handler, __spreadProps$8(__spreadValues$h({}, options), { eventName: "keypress" })); } function onKeyUp(key, handler, options = {}) { return onKeyStroke(key, handler, __spreadProps$8(__spreadValues$h({}, options), { eventName: "keyup" })); } const DEFAULT_DELAY = 500; function onLongPress(target, handler, options) { const elementRef = vueDemi.computed(() => core.unrefElement(target)); let timeout = null; function clear() { if (timeout != null) { clearTimeout(timeout); timeout = null; } } function onDown(ev) { var _a; clear(); timeout = setTimeout(() => handler(ev), (_a = options == null ? void 0 : options.delay) != null ? _a : DEFAULT_DELAY); } core.useEventListener(elementRef, "pointerdown", onDown); core.useEventListener(elementRef, "pointerup", clear); core.useEventListener(elementRef, "pointerleave", clear); } const isFocusedElementEditable = () => { const { activeElement, body } = document; if (!activeElement) return false; if (activeElement === body) return false; switch (activeElement.tagName) { case "INPUT": case "TEXTAREA": return true; } return activeElement.hasAttribute("contenteditable"); }; const isTypedCharValid = ({ keyCode, metaKey, ctrlKey, altKey }) => { if (metaKey || ctrlKey || altKey) return false; if (keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 105) return true; if (keyCode >= 65 && keyCode <= 90) return true; return false; }; function onStartTyping(callback, options = {}) { const { document: document2 = defaultDocument } = options; const keydown = (event) => { !isFocusedElementEditable() && isTypedCharValid(event) && callback(event); }; if (document2) useEventListener(document2, "keydown", keydown, { passive: true }); } function templateRef(key, initialValue = null) { const instance = vueDemi.getCurrentInstance(); let _trigger = () => { }; const element = vueDemi.customRef((track, trigger) => { _trigger = trigger; return { get() { var _a, _b; track(); return (_b = (_a = instance == null ? void 0 : instance.proxy) == null ? void 0 : _a.$refs[key]) != null ? _b : initialValue; }, set() { } }; }); shared.tryOnMounted(_trigger); vueDemi.onUpdated(_trigger); return element; } function useActiveElement(options = {}) { const { window = defaultWindow } = options; const counter = vueDemi.ref(0); if (window) { useEventListener(window, "blur", () => counter.value += 1, true); useEventListener(window, "focus", () => counter.value += 1, true); } return vueDemi.computed(() => { counter.value; return window == null ? void 0 : window.document.activeElement; }); } function useAsyncQueue(tasks, options = {}) { const { interrupt = true, onError = shared.noop, onFinished = shared.noop } = options; const promiseState = { pending: "pending", rejected: "rejected", fulfilled: "fulfilled" }; const initialResult = Array.from(new Array(tasks.length), () => ({ state: promiseState.pending, data: null })); const result = vueDemi.reactive(initialResult); const activeIndex = vueDemi.ref(-1); if (!tasks || tasks.length === 0) { onFinished(); return { activeIndex, result }; } function updateResult(state, res) { activeIndex.value++; result[activeIndex.value].data = res; result[activeIndex.value].state = state; } tasks.reduce((prev, curr) => { return prev.then((prevRes) => { var _a; if (((_a = result[activeIndex.value]) == null ? void 0 : _a.state) === promiseState.rejected && interrupt) { onFinished(); return; } return curr(prevRes).then((currentRes) => { updateResult(promiseState.fulfilled, currentRes); activeIndex.value === tasks.length - 1 && onFinished(); return currentRes; }); }).catch((e) => { updateResult(promiseState.rejected, e); onError(); return e; }); }, Promise.resolve()); return { activeIndex, result }; } function useAsyncState(promise, initialState, options) { const { immediate = true, delay = 0, onError = shared.noop, resetOnExecute = true, shallow = true } = options != null ? options : {}; const state = shallow ? vueDemi.shallowRef(initialState) : vueDemi.ref(initialState); const isReady = vueDemi.ref(false); const isLoading = vueDemi.ref(false); const error = vueDemi.ref(void 0); async function execute(delay2 = 0, ...args) { if (resetOnExecute) state.value = initialState; error.value = void 0; isReady.value = false; isLoading.value = true; if (delay2 > 0) await shared.promiseTimeout(delay2); const _promise = typeof promise === "function" ? promise(...args) : promise; try { const data = await _promise; state.value = data; isReady.value = true; } catch (e) { error.value = e; onError(e); } isLoading.value = false; return state.value; } if (immediate) execute(delay); return { state, isReady, isLoading, error, execute }; } function useBase64(target, options) { const base64 = vueDemi.ref(""); const promise = vueDemi.ref(); function execute() { if (!shared.isClient) return; promise.value = new Promise((resolve, reject) => { try { const _target = vueDemi.unref(target); if (_target === void 0 || _target === null) { resolve(""); } else if (typeof _target === "string") { resolve(blobToBase64(new Blob([_target], { type: "text/plain" }))); } else if (_target instanceof Blob) { resolve(blobToBase64(_target)); } else if (_target instanceof ArrayBuffer) { resolve(window.btoa(String.fromCharCode(...new Uint8Array(_target)))); } else if (_target instanceof HTMLCanvasElement) { resolve(_target.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality)); } else if (_target instanceof HTMLImageElement) { const img = _target.cloneNode(false); img.crossOrigin = "Anonymous"; imgLoaded(img).then(() => { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); resolve(canvas.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality)); }).catch(reject); } else { reject(new Error("target is unsupported types")); } } catch (error) { reject(error); } }); promise.value.then((res) => base64.value = res); return promise.value; } vueDemi.watch(target, execute, { immediate: true }); return { base64, promise, execute }; } function imgLoaded(img) { return new Promise((resolve, reject) => { if (!img.complete) { img.onload = () => { resolve(); }; img.onerror = reject; } else { resolve(); } }); } function blobToBase64(blob) { return new Promise((resolve, reject) => { const fr = new FileReader(); fr.onload = (e) => { resolve(e.target.result); }; fr.onerror = reject; fr.readAsDataURL(blob); }); } function useBattery({ navigator = defaultNavigator } = {}) { const events = ["chargingchange", "chargingtimechange", "dischargingtimechange", "levelchange"]; const isSupported = navigator && "getBattery" in navigator; const charging = vueDemi.ref(false); const chargingTime = vueDemi.ref(0); const dischargingTime = vueDemi.ref(0); const level = vueDemi.ref(1); let battery; function updateBatteryInfo() { charging.value = this.charging; chargingTime.value = this.chargingTime || 0; dischargingTime.value = this.dischargingTime || 0; level.value = this.level; } if (isSupported) { navigator.getBattery().then((_battery) => { battery = _battery; updateBatteryInfo.call(battery); for (const event of events) useEventListener(battery, event, updateBatteryInfo, { passive: true }); }); } return { isSupported, charging, chargingTime, dischargingTime, level }; } function useMediaQuery(query, options = {}) { const { window = defaultWindow } = options; let mediaQuery; const matches = vueDemi.ref(false); const update = () => { if (!window) return; if (!mediaQuery) mediaQuery = window.matchMedia(query); matches.value = mediaQuery.matches; }; shared.tryOnBeforeMount(() => { update(); if (!mediaQuery) return; if ("addEventListener" in mediaQuery) mediaQuery.addEventListener("change", update); else mediaQuery.addListener(update); shared.tryOnScopeDispose(() => { if ("removeEventListener" in mediaQuery) mediaQuery.removeEventListener("change", update); else mediaQuery.removeListener(update); }); }); return matches; } const breakpointsTailwind = { "sm": 640, "md": 768, "lg": 1024, "xl": 1280, "2xl": 1536 }; const breakpointsBootstrapV5 = { sm: 576, md: 768, lg: 992, xl: 1200, xxl: 1400 }; const breakpointsVuetify = { xs: 600, sm: 960, md: 1264, lg: 1904 }; const breakpointsAntDesign = { xs: 480, sm: 576, md: 768, lg: 992, xl: 1200, xxl: 1600 }; const breakpointsQuasar = { xs: 600, sm: 1024, md: 1440, lg: 1920 }; const breakpointsSematic = { mobileS: 320, mobileM: 375, mobileL: 425, tablet: 768, laptop: 1024, laptopL: 1440, desktop4K: 2560 }; var __defProp$g = Object.defineProperty; var __getOwnPropSymbols$i = Object.getOwnPropertySymbols; var __hasOwnProp$i = Object.prototype.hasOwnProperty; var __propIsEnum$i = Object.prototype.propertyIsEnumerable; var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$g = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$i.call(b, prop)) __defNormalProp$g(a, prop, b[prop]); if (__getOwnPropSymbols$i) for (var prop of __getOwnPropSymbols$i(b)) { if (__propIsEnum$i.call(b, prop)) __defNormalProp$g(a, prop, b[prop]); } return a; }; function useBreakpoints(breakpoints, options = {}) { function getValue(k, delta) { let v = breakpoints[k]; if (delta != null) v = shared.increaseWithUnit(v, delta); if (typeof v === "number") v = `${v}px`; return v; } const { window = defaultWindow } = options; function match(query) { if (!window) return false; return window.matchMedia(query).matches; } const greater = (k) => { return useMediaQuery(`(min-width: ${getValue(k)})`, options); }; const shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k) => { Object.defineProperty(shortcuts, k, { get: () => greater(k), enumerable: true, configurable: true }); return shortcuts; }, {}); return __spreadValues$g({ greater, smaller(k) { return useMediaQuery(`(max-width: ${getValue(k, -0.1)})`, options); }, between(a, b) { return useMediaQuery(`(min-width: ${getValue(a)}) and (max-width: ${getValue(b, -0.1)})`, options); }, isGreater(k) { return match(`(min-width: ${getValue(k)})`); }, isSmaller(k) { return match(`(max-width: ${getValue(k, -0.1)})`); }, isInBetween(a, b) { return match(`(min-width: ${getValue(a)}) and (max-width: ${getValue(b, -0.1)})`); } }, shortcutMethods); } const useBroadcastChannel = (options) => { const { name, window = defaultWindow } = options; const isSupported = window && "BroadcastChannel" in window; const isClosed = vueDemi.ref(false); const channel = vueDemi.ref(); const data = vueDemi.ref(); const error = vueDemi.ref(null); const post = (data2) => { if (channel.value) channel.value.postMessage(data2); }; const close = () => { if (channel.value) channel.value.close(); isClosed.value = true; }; if (isSupported) { shared.tryOnMounted(() => { error.value = null; channel.value = new BroadcastChannel(name); channel.value.addEventListener("message", (e) => { data.value = e.data; }, { passive: true }); channel.value.addEventListener("messageerror", (e) => { error.value = e; }, { passive: true }); channel.value.addEventListener("close", () => { isClosed.value = true; }); }); } shared.tryOnScopeDispose(() => { close(); }); return { isSupported, channel, data, post, close, error, isClosed }; }; function useBrowserLocation({ window = defaultWindow } = {}) { const buildState = (trigger) => { const { state: state2, length } = (window == null ? void 0 : window.history) || {}; const { hash, host, hostname, href, origin, pathname, port, protocol, search } = (window == null ? void 0 : window.location) || {}; return { trigger, state: state2, length, hash, host, hostname, href, origin, pathname, port, protocol, search }; }; const state = vueDemi.ref(buildState("load")); if (window) { useEventListener(window, "popstate", () => state.value = buildState("popstate"), { passive: true }); useEventListener(window, "hashchange", () => state.value = buildState("hashchange"), { passive: true }); } return state; } function useCached(refValue, comparator = (a, b) => a === b, watchOptions) { const cachedValue = vueDemi.ref(refValue.value); vueDemi.watch(() => refValue.value, (value) => { if (!comparator(value, cachedValue.value)) cachedValue.value = value; }, watchOptions); return cachedValue; } function useClamp(value, min, max) { const _value = vueDemi.ref(value); return vueDemi.computed({ get() { return _value.value = shared.clamp(_value.value, vueDemi.unref(min), vueDemi.unref(max)); }, set(value2) { _value.value = shared.clamp(value2, vueDemi.unref(min), vueDemi.unref(max)); } }); } function useClipboard(options = {}) { const { navigator = defaultNavigator, read = false, source, copiedDuring = 1500 } = options; const events = ["copy", "cut"]; const isSupported = Boolean(navigator && "clipboard" in navigator); const text = vueDemi.ref(""); const copied = vueDemi.ref(false); const timeout = shared.useTimeoutFn(() => copied.value = false, copiedDuring); function updateText() { navigator.clipboard.readText().then((value) => { text.value = value; }); } if (isSupported && read) { for (const event of events) useEventListener(event, updateText); } async function copy(value = vueDemi.unref(source)) { if (isSupported && value != null) { await navigator.clipboard.writeText(value); text.value = value; copied.value = true; timeout.start(); } } return { isSupported, text, copied, copy }; } const _global = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; const globalKey = "__vueuse_ssr_handlers__"; _global[globalKey] = _global[globalKey] || {}; const handlers = _global[globalKey]; function getSSRHandler(key, fallback) { return handlers[key] || fallback; } function setSSRHandler(key, fn) { handlers[key] = fn; } function guessSerializerType(rawInit) { return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : Array.isArray(rawInit) ? "object" : !Number.isNaN(rawInit) ? "number" : "any"; } const StorageSerializers = { boolean: { read: (v) => v === "true", write: (v) => String(v) }, object: { read: (v) => JSON.parse(v), write: (v) => JSON.stringify(v) }, number: { read: (v) => Number.parseFloat(v), write: (v) => String(v) }, any: { read: (v) => v, write: (v) => String(v) }, string: { read: (v) => v, write: (v) => String(v) }, map: { read: (v) => new Map(JSON.parse(v)), write: (v) => JSON.stringify(Array.from(v.entries())) }, set: { read: (v) => new Set(JSON.parse(v)), write: (v) => JSON.stringify(Array.from(v.entries())) }, date: { read: (v) => new Date(v), write: (v) => v.toISOString() } }; function useStorage(key, initialValue, storage, options = {}) { var _a; const { flush = "pre", deep = true, listenToStorageChanges = true, writeDefaults = true, shallow, window = defaultWindow, eventFilter, onError = (e) => { console.error(e); } } = options; const data = (shallow ? vueDemi.shallowRef : vueDemi.ref)(initialValue); if (!storage) { try { storage = getSSRHandler("getDefaultStorage", () => { var _a2; return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage; })(); } catch (e) { onError(e); } } if (!storage) return data; const rawInit = vueDemi.unref(initialValue); const type = guessSerializerType(rawInit); const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type]; const { pause: pauseWatch, resume: resumeWatch } = shared.pausableWatch(data, () => write(data.value), { flush, deep, eventFilter }); if (window && listenToStorageChanges) useEventListener(window, "storage", update); update(); return data; function write(v) { try { if (v == null) storage.removeItem(key); else storage.setItem(key, serializer.write(v)); } catch (e) { onError(e); } } function read(event) { if (event && event.key !== key) return; pauseWatch(); try { const rawValue = event ? event.newValue : storage.getItem(key); if (rawValue == null) { if (writeDefaults && rawInit !== null) storage.setItem(key, serializer.write(rawInit)); return rawInit; } else if (typeof rawValue !== "string") { return rawValue; } else { return serializer.read(rawValue); } } catch (e) { onError(e); } finally { resumeWatch(); } } function update(event) { if (event && event.key !== key) return; data.value = read(event); } } function usePreferredDark(options) { return useMediaQuery("(prefers-color-scheme: dark)", options); } var __defProp$f = Object.defineProperty; var __getOwnPropSymbols$h = Object.getOwnPropertySymbols; var __hasOwnProp$h = Object.prototype.hasOwnProperty; var __propIsEnum$h = Object.prototype.propertyIsEnumerable; var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$f = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$h.call(b, prop)) __defNormalProp$f(a, prop, b[prop]); if (__getOwnPropSymbols$h) for (var prop of __getOwnPropSymbols$h(b)) { if (__propIsEnum$h.call(b, prop)) __defNormalProp$f(a, prop, b[prop]); } return a; }; function useColorMode(options = {}) { const { selector = "html", attribute = "class", window = defaultWindow, storage, storageKey = "vueuse-color-scheme", listenToStorageChanges = true, storageRef } = options; const modes = __spreadValues$f({ auto: "", light: "light", dark: "dark" }, options.modes || {}); const preferredDark = usePreferredDark({ window }); const preferredMode = vueDemi.computed(() => preferredDark.value ? "dark" : "light"); const store = storageRef || (storageKey == null ? vueDemi.ref("auto") : useStorage(storageKey, "auto", storage, { window, listenToStorageChanges })); const state = vueDemi.computed({ get() { return store.value === "auto" ? preferredMode.value : store.value; }, set(v) { store.value = v; } }); const updateHTMLAttrs = getSSRHandler("updateHTMLAttrs", (selector2, attribute2, value) => { const el = window == null ? void 0 : window.document.querySelector(selector2); if (!el) return; if (attribute2 === "class") { const current = value.split(/\s/g); Object.values(modes).flatMap((i) => (i || "").split(/\s/g)).filter(Boolean).forEach((v) => { if (current.includes(v)) el.classList.add(v); else el.classList.remove(v); }); } else { el.setAttribute(attribute2, value); } }); function defaultOnChanged(mode) { var _a; updateHTMLAttrs(selector, attribute, (_a = modes[mode]) != null ? _a : mode); } function onChanged(mode) { if (options.onChanged) options.onChanged(mode, defaultOnChanged); else defaultOnChanged(mode); } vueDemi.watch(state, onChanged, { flush: "post", immediate: true }); shared.tryOnMounted(() => onChanged(state.value)); return state; } function useConfirmDialog(revealed = vueDemi.ref(false)) { const confirmHook = shared.createEventHook(); const cancelHook = shared.createEventHook(); const revealHook = shared.createEventHook(); let _resolve = shared.noop; const reveal = (data) => { revealHook.trigger(data); revealed.value = true; return new Promise((resolve) => { _resolve = resolve; }); }; const confirm = (data) => { revealed.value = false; confirmHook.trigger(data); _resolve({ data, isCanceled: false }); }; const cancel = (data) => { revealed.value = false; cancelHook.trigger(data); _resolve({ data, isCanceled: true }); }; return { isRevealed: vueDemi.computed(() => revealed.value), reveal, confirm, cancel, onReveal: revealHook.on, onConfirm: confirmHook.on, onCancel: cancelHook.on }; } function useCssVar(prop, target, { window = defaultWindow } = {}) { const variable = vueDemi.ref(""); const elRef = vueDemi.computed(() => { var _a; return unrefElement(target) || ((_a = window == null ? void 0 : window.document) == null ? void 0 : _a.documentElement); }); vueDemi.watch([elRef, () => vueDemi.unref(prop)], ([el, prop2]) => { if (el && window) variable.value = window.getComputedStyle(el).getPropertyValue(prop2); }, { immediate: true }); vueDemi.watch(variable, (val) => { var _a; if ((_a = elRef.value) == null ? void 0 : _a.style) elRef.value.style.setProperty(vueDemi.unref(prop), val); }); return variable; } function useCycleList(list, options) { var _a; const state = vueDemi.shallowRef((_a = options == null ? void 0 : options.initialValue) != null ? _a : list[0]); const index = vueDemi.computed({ get() { var _a2; let index2 = (options == null ? void 0 : options.getIndexOf) ? options.getIndexOf(state.value, list) : list.indexOf(state.value); if (index2 < 0) index2 = (_a2 = options == null ? void 0 : options.fallbackIndex) != null ? _a2 : 0; return index2; }, set(v) { set(v); } }); function set(i) { const length = list.length; const index2 = (i % length + length) % length; const value = list[index2]; state.value = value; return value; } function shift(delta = 1) { return set(index.value + delta); } function next(n = 1) { return shift(n); } function prev(n = 1) { return shift(-n); } return { state, index, next, prev }; } var __defProp$e = Object.defineProperty; var __defProps$7 = Object.defineProperties; var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$g = Object.getOwnPropertySymbols; var __hasOwnProp$g = Object.prototype.hasOwnProperty; var __propIsEnum$g = Object.prototype.propertyIsEnumerable; var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$e = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$g.call(b, prop)) __defNormalProp$e(a, prop, b[prop]); if (__getOwnPropSymbols$g) for (var prop of __getOwnPropSymbols$g(b)) { if (__propIsEnum$g.call(b, prop)) __defNormalProp$e(a, prop, b[prop]); } return a; }; var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b)); function useDark(options = {}) { const { valueDark = "dark", valueLight = "", window = defaultWindow } = options; const mode = useColorMode(__spreadProps$7(__spreadValues$e({}, options), { onChanged: (mode2, defaultHandler) => { var _a; if (options.onChanged) (_a = options.onChanged) == null ? void 0 : _a.call(options, mode2 === "dark"); else defaultHandler(mode2); }, modes: { dark: valueDark, light: valueLight } })); const preferredDark = usePreferredDark({ window }); const isDark = vueDemi.computed({ get() { return mode.value === "dark"; }, set(v) { if (v === preferredDark.value) mode.value = "auto"; else mode.value = v ? "dark" : "light"; } }); return isDark; } const fnClone = (v) => JSON.parse(JSON.stringify(v)); const fnBypass = (v) => v; const fnSetSource = (source, value) => source.value = value; function defaultDump(clone) { return clone ? shared.isFunction(clone) ? clone : fnClone : fnBypass; } function defaultParse(clone) { return clone ? shared.isFunction(clone) ? clone : fnClone : fnBypass; } function useManualRefHistory(source, options = {}) { const { clone = false, dump = defaultDump(clone), parse = defaultParse(clone), setSource = fnSetSource } = options; function _createHistoryRecord() { return vueDemi.markRaw({ snapshot: dump(source.value), timestamp: shared.timestamp() }); } const last = vueDemi.ref(_createHistoryRecord()); const undoStack = vueDemi.ref([]); const redoStack = vueDemi.ref([]); const _setSource = (record) => { setSource(source, parse(record.snapshot)); last.value = record; }; const commit = () => { undoStack.value.unshift(last.value); last.value = _createHistoryRecord(); if (options.capacity && undoStack.value.length > options.capacity) undoStack.value.splice(options.capacity, Infinity); if (redoStack.value.length) redoStack.value.splice(0, redoStack.value.length); }; const clear = () => { undoStack.value.splice(0, undoStack.value.length); redoStack.value.splice(0, redoStack.value.length); }; const undo = () => { const state = undoStack.value.shift(); if (state) { redoStack.value.unshift(last.value); _setSource(state); } }; const redo = () => { const state = redoStack.value.shift(); if (state) { undoStack.value.unshift(last.value); _setSource(state); } }; const reset = () => { _setSource(last.value); }; const history = vueDemi.computed(() => [last.value, ...undoStack.value]); const canUndo = vueDemi.computed(() => undoStack.value.length > 0); const canRedo = vueDemi.computed(() => redoStack.value.length > 0); return { source, undoStack, redoStack, last, history, canUndo, canRedo, clear, commit, reset, undo, redo }; } var __defProp$d = Object.defineProperty; var __defProps$6 = Object.defineProperties; var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$f = Object.getOwnPropertySymbols; var __hasOwnProp$f = Object.prototype.hasOwnProperty; var __propIsEnum$f = Object.prototype.propertyIsEnumerable; var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$d = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$f.call(b, prop)) __defNormalProp$d(a, prop, b[prop]); if (__getOwnPropSymbols$f) for (var prop of __getOwnPropSymbols$f(b)) { if (__propIsEnum$f.call(b, prop)) __defNormalProp$d(a, prop, b[prop]); } return a; }; var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b)); function useRefHistory(source, options = {}) { const { deep = false, flush = "pre", eventFilter } = options; const { eventFilter: composedFilter, pause, resume: resumeTracking, isActive: isTracking } = shared.pausableFilter(eventFilter); const { ignoreUpdates, ignorePrevAsyncUpdates, stop } = shared.watchIgnorable(source, commit, { deep, flush, eventFilter: composedFilter }); function setSource(source2, value) { ignorePrevAsyncUpdates(); ignoreUpdates(() => { source2.value = value; }); } const manualHistory = useManualRefHistory(source, __spreadProps$6(__spreadValues$d({}, options), { clone: options.clone || deep, setSource })); const { clear, commit: manualCommit } = manualHistory; function commit() { ignorePrevAsyncUpdates(); manualCommit(); } function resume(commitNow) { resumeTracking(); if (commitNow) commit(); } function batch(fn) { let canceled = false; const cancel = () => canceled = true; ignoreUpdates(() => { fn(cancel); }); if (!canceled) commit(); } function dispose() { stop(); clear(); } return __spreadProps$6(__spreadValues$d({}, manualHistory), { isTracking, pause, resume, commit, batch, dispose }); } var __defProp$c = Object.defineProperty; var __defProps$5 = Object.defineProperties; var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$e = Object.getOwnPropertySymbols; var __hasOwnProp$e = Object.prototype.hasOwnProperty; var __propIsEnum$e = Object.prototype.propertyIsEnumerable; var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$c = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$e.call(b, prop)) __defNormalProp$c(a, prop, b[prop]); if (__getOwnPropSymbols$e) for (var prop of __getOwnPropSymbols$e(b)) { if (__propIsEnum$e.call(b, prop)) __defNormalProp$c(a, prop, b[prop]); } return a; }; var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b)); function useDebouncedRefHistory(source, options = {}) { const filter = options.debounce ? shared.debounceFilter(options.debounce) : void 0; const history = useRefHistory(source, __spreadProps$5(__spreadValues$c({}, options), { eventFilter: filter })); return __spreadValues$c({}, history); } function useDeviceMotion(options = {}) { const { window = defaultWindow, eventFilter = shared.bypassFilter } = options; const acceleration = vueDemi.ref({ x: null, y: null, z: null }); const rotationRate = vueDemi.ref({ alpha: null, beta: null, gamma: null }); const interval = vueDemi.ref(0); const accelerationIncludingGravity = vueDemi.ref({ x: null, y: null, z: null }); if (window) { const onDeviceMotion = shared.createFilterWrapper(eventFilter, (event) => { acceleration.value = event.acceleration; accelerationIncludingGravity.value = event.accelerationIncludingGravity; rotationRate.value = event.rotationRate; interval.value = event.interval; }); useEventListener(window, "devicemotion", onDeviceMotion); } return { acceleration, accelerationIncludingGravity, rotationRate, interval }; } function useDeviceOrientation(options = {}) { const { window = defaultWindow } = options; const isSupported = Boolean(window && "DeviceOrientationEvent" in window); const isAbsolute = vueDemi.ref(false); const alpha = vueDemi.ref(null); const beta = vueDemi.ref(null); const gamma = vueDemi.ref(null); if (window && isSupported) { useEventListener(window, "deviceorientation", (event) => { isAbsolute.value = event.absolute; alpha.value = event.alpha; beta.value = event.beta; gamma.value = event.gamma; }); } return { isSupported, isAbsolute, alpha, beta, gamma }; } const DEVICE_PIXEL_RATIO_SCALES = [ 1, 1.325, 1.4, 1.5, 1.8, 2, 2.4, 2.5, 2.75, 3, 3.5, 4 ]; function useDevicePixelRatio({ window = defaultWindow } = {}) { if (!window) { return { pixelRatio: vueDemi.ref(1) }; } const pixelRatio = vueDemi.ref(window.devicePixelRatio); const handleDevicePixelRatio = () => { pixelRatio.value = window.devicePixelRatio; }; useEventListener(window, "resize", handleDevicePixelRatio, { passive: true }); DEVICE_PIXEL_RATIO_SCALES.forEach((dppx) => { const mqlMin = useMediaQuery(`screen and (min-resolution: ${dppx}dppx)`); const mqlMax = useMediaQuery(`screen and (max-resolution: ${dppx}dppx)`); vueDemi.watch([mqlMin, mqlMax], handleDevicePixelRatio); }); return { pixelRatio }; } function usePermission(permissionDesc, options = {}) { const { controls = false, navigator = defaultNavigator } = options; const isSupported = Boolean(navigator && "permissions" in navigator); let permissionStatus; const desc = typeof permissionDesc === "string" ? { name: permissionDesc } : permissionDesc; const state = vueDemi.ref(); const onChange = () => { if (permissionStatus) state.value = permissionStatus.state; }; const query = shared.createSingletonPromise(async () => { if (!isSupported) return; if (!permissionStatus) { try { permissionStatus = await navigator.permissions.query(desc); useEventListener(permissionStatus, "change", onChange); onChange(); } catch (e) { state.value = "prompt"; } } return permissionStatus; }); query(); if (controls) { return { state, isSupported, query }; } else { return state; } } function useDevicesList(options = {}) { const { navigator = defaultNavigator, requestPermissions = false, constraints = { audio: true, video: true }, onUpdated } = options; const devices = vueDemi.ref([]); const videoInputs = vueDemi.computed(() => devices.value.filter((i) => i.kind === "videoinput")); const audioInputs = vueDemi.computed(() => devices.value.filter((i) => i.kind === "audioinput")); const audioOutputs = vueDemi.computed(() => devices.value.filter((i) => i.kind === "audiooutput")); let isSupported = false; const permissionGranted = vueDemi.ref(false); async function update() { if (!isSupported) return; devices.value = await navigator.mediaDevices.enumerateDevices(); onUpdated == null ? void 0 : onUpdated(devices.value); } async function ensurePermissions() { if (!isSupported) return false; if (permissionGranted.value) return true; const { state, query } = usePermission("camera", { controls: true }); await query(); if (state.value !== "granted") { const stream = await navigator.mediaDevices.getUserMedia(constraints); stream.getTracks().forEach((t) => t.stop()); update(); permissionGranted.value = true; } else { permissionGranted.value = true; } return permissionGranted.value; } if (navigator) { isSupported = Boolean(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices); if (isSupported) { if (requestPermissions) ensurePermissions(); useEventListener(navigator.mediaDevices, "devicechange", update); update(); } } return { devices, ensurePermissions, permissionGranted, videoInputs, audioInputs, audioOutputs, isSupported }; } function useDisplayMedia(options = {}) { var _a, _b; const enabled = vueDemi.ref((_a = options.enabled) != null ? _a : false); const video = options.video; const audio = options.audio; const { navigator = defaultNavigator } = options; const isSupported = Boolean((_b = navigator == null ? void 0 : navigator.mediaDevices) == null ? void 0 : _b.getDisplayMedia); const constraint = { audio, video }; const stream = vueDemi.shallowRef(); async function _start() { if (!isSupported || stream.value) return; stream.value = await navigator.mediaDevices.getDisplayMedia(constraint); return stream.value; } async function _stop() { var _a2; (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop()); stream.value = void 0; } function stop() { _stop(); enabled.value = false; } async function start() { await _start(); if (stream.value) enabled.value = true; return stream.value; } vueDemi.watch(enabled, (v) => { if (v) _start(); else _stop(); }, { immediate: true }); return { isSupported, stream, start, stop, enabled }; } function useDocumentVisibility({ document = defaultDocument } = {}) { if (!document) return vueDemi.ref("visible"); const visibility = vueDemi.ref(document.visibilityState); useEventListener(document, "visibilitychange", () => { visibility.value = document.visibilityState; }); return visibility; } var __defProp$b = Object.defineProperty; var __defProps$4 = Object.defineProperties; var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$d = Object.getOwnPropertySymbols; var __hasOwnProp$d = Object.prototype.hasOwnProperty; var __propIsEnum$d = Object.prototype.propertyIsEnumerable; var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$b = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$d.call(b, prop)) __defNormalProp$b(a, prop, b[prop]); if (__getOwnPropSymbols$d) for (var prop of __getOwnPropSymbols$d(b)) { if (__propIsEnum$d.call(b, prop)) __defNormalProp$b(a, prop, b[prop]); } return a; }; var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b)); function useDraggable(target, options = {}) { var _a, _b; const draggingElement = (_a = options.draggingElement) != null ? _a : defaultWindow; const position = vueDemi.ref((_b = options.initialValue) != null ? _b : { x: 0, y: 0 }); const pressedDelta = vueDemi.ref(); const filterEvent = (e) => { if (options.pointerTypes) return options.pointerTypes.includes(e.pointerType); return true; }; const handleEvent = (e) => { if (vueDemi.unref(options.preventDefault)) e.preventDefault(); if (vueDemi.unref(options.stopPropagation)) e.stopPropagation(); }; const start = (e) => { var _a2; if (!filterEvent(e)) return; if (vueDemi.unref(options.exact) && e.target !== vueDemi.unref(target)) return; const rect = vueDemi.unref(target).getBoundingClientRect(); const pos = { x: e.pageX - rect.left, y: e.pageY - rect.top }; if (((_a2 = options.onStart) == null ? void 0 : _a2.call(options, pos, e)) === false) return; pressedDelta.value = pos; handleEvent(e); }; const move = (e) => { var _a2; if (!filterEvent(e)) return; if (!pressedDelta.value) return; position.value = { x: e.pageX - pressedDelta.value.x, y: e.pageY - pressedDelta.value.y }; (_a2 = options.onMove) == null ? void 0 : _a2.call(options, position.value, e); handleEvent(e); }; const end = (e) => { var _a2; if (!filterEvent(e)) return; if (!pressedDelta.value) return; pressedDelta.value = void 0; (_a2 = options.onEnd) == null ? void 0 : _a2.call(options, position.value, e); handleEvent(e); }; if (shared.isClient) { useEventListener(target, "pointerdown", start, true); useEventListener(draggingElement, "pointermove", move, true); useEventListener(draggingElement, "pointerup", end, true); } return __spreadProps$4(__spreadValues$b({}, shared.toRefs(position)), { position, isDragging: vueDemi.computed(() => !!pressedDelta.value), style: vueDemi.computed(() => `left:${position.value.x}px;top:${position.value.y}px;`) }); } var __getOwnPropSymbols$c = Object.getOwnPropertySymbols; var __hasOwnProp$c = Object.prototype.hasOwnProperty; var __propIsEnum$c = Object.prototype.propertyIsEnumerable; var __objRest$2 = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp$c.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols$c) for (var prop of __getOwnPropSymbols$c(source)) { if (exclude.indexOf(prop) < 0 && __propIsEnum$c.call(source, prop)) target[prop] = source[prop]; } return target; }; function useResizeObserver(target, callback, options = {}) { const _a = options, { window = defaultWindow } = _a, observerOptions = __objRest$2(_a, ["window"]); let observer; const isSupported = window && "ResizeObserver" in window; const cleanup = () => { if (observer) { observer.disconnect(); observer = void 0; } }; const stopWatch = vueDemi.watch(() => unrefElement(target), (el) => { cleanup(); if (isSupported && window && el) { observer = new ResizeObserver(callback); observer.observe(el, observerOptions); } }, { immediate: true, flush: "post" }); const stop = () => { cleanup(); stopWatch(); }; shared.tryOnScopeDispose(stop); return { isSupported, stop }; } function useElementBounding(target) { const height = vueDemi.ref(0); const bottom = vueDemi.ref(0); const left = vueDemi.ref(0); const right = vueDemi.ref(0); const top = vueDemi.ref(0); const width = vueDemi.ref(0); const x = vueDemi.ref(0); const y = vueDemi.ref(0); function update() { const el = unrefElement(target); if (!el) { height.value = 0; bottom.value = 0; left.value = 0; right.value = 0; top.value = 0; width.value = 0; x.value = 0; y.value = 0; return; } const rect = el.getBoundingClientRect(); height.value = rect.height; bottom.value = rect.bottom; left.value = rect.left; right.value = rect.right; top.value = rect.top; width.value = rect.width; x.value = rect.x; y.value = rect.y; } useEventListener("scroll", update, true); useResizeObserver(target, update); vueDemi.watch(() => unrefElement(target), (ele) => !ele && update()); return { height, bottom, left, right, top, width, x, y, update }; } function useRafFn(fn, options = {}) { const { immediate = true, window = defaultWindow } = options; const isActive = vueDemi.ref(false); function loop() { if (!isActive.value || !window) return; fn(); window.requestAnimationFrame(loop); } function resume() { if (!isActive.value && window) { isActive.value = true; loop(); } } function pause() { isActive.value = false; } if (immediate) resume(); shared.tryOnScopeDispose(pause); return { isActive, pause, resume }; } var __defProp$a = Object.defineProperty; var __getOwnPropSymbols$b = Object.getOwnPropertySymbols; var __hasOwnProp$b = Object.prototype.hasOwnProperty; var __propIsEnum$b = Object.prototype.propertyIsEnumerable; var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$a = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$b.call(b, prop)) __defNormalProp$a(a, prop, b[prop]); if (__getOwnPropSymbols$b) for (var prop of __getOwnPropSymbols$b(b)) { if (__propIsEnum$b.call(b, prop)) __defNormalProp$a(a, prop, b[prop]); } return a; }; function useElementByPoint(options) { const element = vueDemi.ref(null); const { x, y } = options; const controls = useRafFn(() => { element.value = document.elementFromPoint(vueDemi.unref(x), vueDemi.unref(y)); }); return __spreadValues$a({ element }, controls); } function useElementHover(el) { const isHovered = vueDemi.ref(false); useEventListener(el, "mouseenter", () => isHovered.value = true); useEventListener(el, "mouseleave", () => isHovered.value = false); return isHovered; } function useElementSize(target, initialSize = { width: 0, height: 0 }, options = {}) { const width = vueDemi.ref(initialSize.width); const height = vueDemi.ref(initialSize.height); useResizeObserver(target, ([entry]) => { width.value = entry.contentRect.width; height.value = entry.contentRect.height; }, options); vueDemi.watch(() => unrefElement(target), (ele) => { width.value = ele ? initialSize.width : 0; height.value = ele ? initialSize.height : 0; }); return { width, height }; } function useElementVisibility(element, { window = defaultWindow, scrollTarget } = {}) { const elementIsVisible = vueDemi.ref(false); const testBounding = () => { if (!window) return; const document = window.document; if (!vueDemi.unref(element)) { elementIsVisible.value = false; } else { const rect = vueDemi.unref(element).getBoundingClientRect(); elementIsVisible.value = rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth) && rect.bottom >= 0 && rect.right >= 0; } }; shared.tryOnMounted(testBounding); if (window) shared.tryOnMounted(() => useEventListener(vueDemi.unref(scrollTarget) || window, "scroll", testBounding, { capture: false, passive: true })); return elementIsVisible; } const events = /* @__PURE__ */ new Map(); function useEventBus(key) { const scope = vueDemi.getCurrentScope(); function on(listener) { const listeners = events.get(key) || []; listeners.push(listener); events.set(key, listeners); const _off = () => off(listener); scope == null ? void 0 : scope.cleanups.push(_off); return _off; } function once(listener) { function _listener(...args) { off(_listener); listener(...args); } return on(_listener); } function off(listener) { const listeners = events.get(key); if (!listeners) return; const index = listeners.indexOf(listener); if (index > -1) listeners.splice(index, 1); if (!listeners.length) events.delete(key); } function reset() { events.delete(key); } function emit(event, payload) { var _a; (_a = events.get(key)) == null ? void 0 : _a.forEach((v) => v(event, payload)); } return { on, once, off, emit, reset }; } function useEventSource(url, events = [], options = {}) { const event = vueDemi.ref(null); const data = vueDemi.ref(null); const status = vueDemi.ref("CONNECTING"); const eventSource = vueDemi.ref(null); const error = vueDemi.ref(null); const { withCredentials = false } = options; const close = () => { if (eventSource.value) { eventSource.value.close(); eventSource.value = null; status.value = "CLOSED"; } }; const es = new EventSource(url, { withCredentials }); eventSource.value = es; es.onopen = () => { status.value = "OPEN"; error.value = null; }; es.onerror = (e) => { status.value = "CLOSED"; error.value = e; }; es.onmessage = (e) => { event.value = null; data.value = e.data; }; for (const event_name of events) { useEventListener(es, event_name, (e) => { event.value = event_name; data.value = e.data || null; }); } shared.tryOnScopeDispose(() => { close(); }); return { eventSource, event, data, status, error, close }; } function useEyeDropper(options = {}) { const { initialValue = "" } = options; const isSupported = Boolean(typeof window !== "undefined" && "EyeDropper" in window); const sRGBHex = vueDemi.ref(initialValue); async function open(openOptions) { if (!isSupported) return; const eyeDropper = new window.EyeDropper(); const result = await eyeDropper.open(openOptions); sRGBHex.value = result.sRGBHex; return result; } return { isSupported, sRGBHex, open }; } function useFavicon(newIcon = null, options = {}) { const { baseUrl = "", rel = "icon", document = defaultDocument } = options; const favicon = vueDemi.isRef(newIcon) ? newIcon : vueDemi.ref(newIcon); const applyIcon = (icon) => { document == null ? void 0 : document.head.querySelectorAll(`link[rel*="${rel}"]`).forEach((el) => el.href = `${baseUrl}${icon}`); }; vueDemi.watch(favicon, (i, o) => { if (shared.isString(i) && i !== o) applyIcon(i); }, { immediate: true }); return favicon; } var __defProp$9 = Object.defineProperty; var __defProps$3 = Object.defineProperties; var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$a = Object.getOwnPropertySymbols; var __hasOwnProp$a = Object.prototype.hasOwnProperty; var __propIsEnum$a = Object.prototype.propertyIsEnumerable; var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$9 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$a.call(b, prop)) __defNormalProp$9(a, prop, b[prop]); if (__getOwnPropSymbols$a) for (var prop of __getOwnPropSymbols$a(b)) { if (__propIsEnum$a.call(b, prop)) __defNormalProp$9(a, prop, b[prop]); } return a; }; var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); const payloadMapping = { json: "application/json", text: "text/plain", formData: "multipart/form-data" }; function isFetchOptions(obj) { return shared.containsProp(obj, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError"); } function headersToObject(headers) { if (headers instanceof Headers) return Object.fromEntries([...headers.entries()]); return headers; } function createFetch(config = {}) { const _options = config.options || {}; const _fetchOptions = config.fetchOptions || {}; function useFactoryFetch(url, ...args) { const computedUrl = vueDemi.computed(() => config.baseUrl ? joinPaths(vueDemi.unref(config.baseUrl), vueDemi.unref(url)) : vueDemi.unref(url)); let options = _options; let fetchOptions = _fetchOptions; if (args.length > 0) { if (isFetchOptions(args[0])) { options = __spreadValues$9(__spreadValues$9({}, options), args[0]); } else { fetchOptions = __spreadProps$3(__spreadValues$9(__spreadValues$9({}, fetchOptions), args[0]), { headers: __spreadValues$9(__spreadValues$9({}, headersToObject(fetchOptions.headers) || {}), headersToObject(args[0].headers) || {}) }); } } if (args.length > 1 && isFetchOptions(args[1])) options = __spreadValues$9(__spreadValues$9({}, options), args[1]); return useFetch(computedUrl, fetchOptions, options); } return useFactoryFetch; } function useFetch(url, ...args) { var _a; const supportsAbort = typeof AbortController === "function"; let fetchOptions = {}; let options = { immediate: true, refetch: false, timeout: 0 }; const config = { method: "GET", type: "text", payload: void 0 }; if (args.length > 0) { if (isFetchOptions(args[0])) options = __spreadValues$9(__spreadValues$9({}, options), args[0]); else fetchOptions = args[0]; } if (args.length > 1) { if (isFetchOptions(args[1])) options = __spreadValues$9(__spreadValues$9({}, options), args[1]); } const { fetch = (_a = defaultWindow) == null ? void 0 : _a.fetch, initialData, timeout } = options; const responseEvent = shared.createEventHook(); const errorEvent = shared.createEventHook(); const finallyEvent = shared.createEventHook(); const isFinished = vueDemi.ref(false); const isFetching = vueDemi.ref(false); const aborted = vueDemi.ref(false); const statusCode = vueDemi.ref(null); const response = vueDemi.shallowRef(null); const error = vueDemi.shallowRef(null); const data = vueDemi.shallowRef(initialData); const canAbort = vueDemi.computed(() => supportsAbort && isFetching.value); let controller; let timer; const abort = () => { if (supportsAbort && controller) controller.abort(); }; const loading = (isLoading) => { isFetching.value = isLoading; isFinished.value = !isLoading; }; if (timeout) timer = shared.useTimeoutFn(abort, timeout, { immediate: false }); const execute = async (throwOnFailed = false) => { var _a2; loading(true); error.value = null; statusCode.value = null; aborted.value = false; controller = void 0; if (supportsAbort) { controller = new AbortController(); controller.signal.onabort = () => aborted.value = true; fetchOptions = __spreadProps$3(__spreadValues$9({}, fetchOptions), { signal: controller.signal }); } const defaultFetchOptions = { method: config.method, headers: {} }; if (config.payload) { const headers = headersToObject(defaultFetchOptions.headers); if (config.payloadType) headers["Content-Type"] = (_a2 = payloadMapping[config.payloadType]) != null ? _a2 : config.payloadType; defaultFetchOptions.body = config.payloadType === "json" ? JSON.stringify(vueDemi.unref(config.payload)) : vueDemi.unref(config.payload); } let isCanceled = false; const context = { url: vueDemi.unref(url), options: fetchOptions, cancel: () => { isCanceled = true; } }; if (options.beforeFetch) Object.assign(context, await options.beforeFetch(context)); if (isCanceled || !fetch) { loading(false); return Promise.resolve(null); } let responseData = null; if (timer) timer.start(); return new Promise((resolve, reject) => { var _a3; fetch(context.url, __spreadProps$3(__spreadValues$9(__spreadValues$9({}, defaultFetchOptions), context.options), { headers: __spreadValues$9(__spreadValues$9({}, headersToObject(defaultFetchOptions.headers)), headersToObject((_a3 = context.options) == null ? void 0 : _a3.headers)) })).then(async (fetchResponse) => { response.value = fetchResponse; statusCode.value = fetchResponse.status; responseData = await fetchResponse[config.type](); if (options.afterFetch && statusCode.value >= 200 && statusCode.value < 300) ({ data: responseData } = await options.afterFetch({ data: responseData, response: fetchResponse })); data.value = responseData; if (!fetchResponse.ok) throw new Error(fetchResponse.statusText); responseEvent.trigger(fetchResponse); return resolve(fetchResponse); }).catch(async (fetchError) => { let errorData = fetchError.message || fetchError.name; if (options.onFetchError) ({ data: responseData, error: errorData } = await options.onFetchError({ data: responseData, error: fetchError })); data.value = responseData; error.value = errorData; errorEvent.trigger(fetchError); if (throwOnFailed) return reject(fetchError); return resolve(null); }).finally(() => { loading(false); if (timer) timer.stop(); finallyEvent.trigger(null); }); }); }; vueDemi.watch(() => [ vueDemi.unref(url), vueDemi.unref(options.refetch) ], () => vueDemi.unref(options.refetch) && execute(), { deep: true }); const shell = { isFinished, statusCode, response, error, data, isFetching, canAbort, aborted, abort, execute, onFetchResponse: responseEvent.on, onFetchError: errorEvent.on, onFetchFinally: finallyEvent.on, get: setMethod("GET"), put: setMethod("PUT"), post: setMethod("POST"), delete: setMethod("DELETE"), patch: setMethod("PATCH"), head: setMethod("HEAD"), options: setMethod("OPTIONS"), json: setType("json"), text: setType("text"), blob: setType("blob"), arrayBuffer: setType("arrayBuffer"), formData: setType("formData") }; function setMethod(method) { return (payload, payloadType) => { if (!isFetching.value) { config.method = method; config.payload = payload; config.payloadType = payloadType; if (vueDemi.isRef(config.payload)) { vueDemi.watch(() => [ vueDemi.unref(config.payload), vueDemi.unref(options.refetch) ], () => vueDemi.unref(options.refetch) && execute(), { deep: true }); } if (!payloadType && vueDemi.unref(payload) && Object.getPrototypeOf(vueDemi.unref(payload)) === Object.prototype) config.payloadType = "json"; return shell; } return void 0; }; } function waitUntilFinished() { return new Promise((resolve, reject) => { shared.until(isFinished).toBe(true).then(() => resolve(shell)).catch((error2) => reject(error2)); }); } function setType(type) { return () => { if (!isFetching.value) { config.type = type; return __spreadProps$3(__spreadValues$9({}, shell), { then(onFulfilled, onRejected) { return waitUntilFinished().then(onFulfilled, onRejected); } }); } return void 0; }; } if (options.immediate) setTimeout(execute, 0); return __spreadProps$3(__spreadValues$9({}, shell), { then(onFulfilled, onRejected) { return waitUntilFinished().then(onFulfilled, onRejected); } }); } function joinPaths(start, end) { if (!start.endsWith("/") && !end.startsWith("/")) return `${start}/${end}`; return `${start}${end}`; } var __defProp$8 = Object.defineProperty; var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols; var __hasOwnProp$9 = Object.prototype.hasOwnProperty; var __propIsEnum$9 = Object.prototype.propertyIsEnumerable; var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$8 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$9.call(b, prop)) __defNormalProp$8(a, prop, b[prop]); if (__getOwnPropSymbols$9) for (var prop of __getOwnPropSymbols$9(b)) { if (__propIsEnum$9.call(b, prop)) __defNormalProp$8(a, prop, b[prop]); } return a; }; function useFileSystemAccess(options = {}) { const { window: _window = defaultWindow, dataType = "Text" } = vueDemi.unref(options); const window = _window; const isSupported = Boolean(window && "showSaveFilePicker" in window && "showOpenFilePicker" in window); const fileHandle = vueDemi.ref(); const data = vueDemi.ref(); const file = vueDemi.ref(); const fileName = vueDemi.computed(() => { var _a, _b; return (_b = (_a = file.value) == null ? void 0 : _a.name) != null ? _b : ""; }); const fileMIME = vueDemi.computed(() => { var _a, _b; return (_b = (_a = file.value) == null ? void 0 : _a.type) != null ? _b : ""; }); const fileSize = vueDemi.computed(() => { var _a, _b; return (_b = (_a = file.value) == null ? void 0 : _a.size) != null ? _b : 0; }); const fileLastModified = vueDemi.computed(() => { var _a, _b; return (_b = (_a = file.value) == null ? void 0 : _a.lastModified) != null ? _b : 0; }); async function open(_options = {}) { if (!isSupported) return; const [handle] = await window.showOpenFilePicker(__spreadValues$8(__spreadValues$8({}, vueDemi.unref(options)), _options)); fileHandle.value = handle; await updateFile(); await updateData(); } async function create(_options = {}) { if (!isSupported) return; fileHandle.value = await window.showSaveFilePicker(__spreadValues$8(__spreadValues$8({}, vueDemi.unref(options)), _options)); data.value = void 0; await updateFile(); await updateData(); } async function save(_options = {}) { if (!isSupported) return; if (!fileHandle.value) return saveAs(_options); if (data.value) { const writableStream = await fileHandle.value.createWritable(); await writableStream.write(data.value); await writableStream.close(); } await updateFile(); } async function saveAs(_options = {}) { if (!isSupported) return; fileHandle.value = await window.showSaveFilePicker(__spreadValues$8(__spreadValues$8({}, vueDemi.unref(options)), _options)); if (data.value) { const writableStream = await fileHandle.value.createWritable(); await writableStream.write(data.value); await writableStream.close(); } await updateFile(); } async function updateFile() { var _a; file.value = await ((_a = fileHandle.value) == null ? void 0 : _a.getFile()); } async function updateData() { var _a, _b; if (vueDemi.unref(dataType) === "Text") data.value = await ((_a = file.value) == null ? void 0 : _a.text()); if (vueDemi.unref(dataType) === "ArrayBuffer") data.value = await ((_b = file.value) == null ? void 0 : _b.arrayBuffer()); if (vueDemi.unref(dataType) === "Blob") data.value = file.value; } vueDemi.watch(() => vueDemi.unref(dataType), updateData); return { isSupported, data, file, fileName, fileMIME, fileSize, fileLastModified, open, create, save, saveAs, updateData }; } function useFocus(target, options = {}) { const { initialValue = false } = options; const activeElement = useActiveElement(options); const targetElement = vueDemi.computed(() => unrefElement(target)); const focused = vueDemi.computed({ get() { return activeElement.value === targetElement.value; }, set(value) { var _a, _b; if (!value && focused.value) (_a = targetElement.value) == null ? void 0 : _a.blur(); if (value && !focused.value) (_b = targetElement.value) == null ? void 0 : _b.focus(); } }); vueDemi.watch(targetElement, () => { focused.value = initialValue; }, { immediate: true, flush: "post" }); return { focused }; } function useFocusWithin(target, options = {}) { const activeElement = useActiveElement(options); const targetElement = vueDemi.computed(() => unrefElement(target)); const focused = vueDemi.computed(() => targetElement.value && activeElement.value ? targetElement.value.contains(activeElement.value) : false); return { focused }; } function useFps(options) { var _a; const fps = vueDemi.ref(0); if (typeof performance === "undefined") return fps; const every = (_a = options == null ? void 0 : options.every) != null ? _a : 10; let last = performance.now(); let ticks = 0; useRafFn(() => { ticks += 1; if (ticks >= every) { const now = performance.now(); const diff = now - last; fps.value = Math.round(1e3 / (diff / ticks)); last = now; ticks = 0; } }); return fps; } const functionsMap = [ [ "requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror" ], [ "webkitRequestFullscreen", "webkitExitFullscreen", "webkitFullscreenElement", "webkitFullscreenEnabled", "webkitfullscreenchange", "webkitfullscreenerror" ], [ "webkitRequestFullScreen", "webkitCancelFullScreen", "webkitCurrentFullScreenElement", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitfullscreenerror" ], [ "mozRequestFullScreen", "mozCancelFullScreen", "mozFullScreenElement", "mozFullScreenEnabled", "mozfullscreenchange", "mozfullscreenerror" ], [ "msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError" ] ]; function useFullscreen(target, options = {}) { const { document = defaultDocument, autoExit = false } = options; const targetRef = target || (document == null ? void 0 : document.querySelector("html")); const isFullscreen = vueDemi.ref(false); let isSupported = false; let map = functionsMap[0]; if (!document) { isSupported = false; } else { for (const m of functionsMap) { if (m[1] in document) { map = m; isSupported = true; break; } } } const [REQUEST, EXIT, ELEMENT, , EVENT] = map; async function exit() { if (!isSupported) return; if (document == null ? void 0 : document[ELEMENT]) await document[EXIT](); isFullscreen.value = false; } async function enter() { if (!isSupported) return; await exit(); const target2 = unrefElement(targetRef); if (target2) { await target2[REQUEST](); isFullscreen.value = true; } } async function toggle() { if (isFullscreen.value) await exit(); else await enter(); } if (document) { useEventListener(document, EVENT, () => { isFullscreen.value = !!(document == null ? void 0 : document[ELEMENT]); }, false); } if (autoExit) shared.tryOnScopeDispose(exit); return { isSupported, isFullscreen, enter, exit, toggle }; } function mapGamepadToXbox360Controller(gamepad) { return vueDemi.computed(() => { if (gamepad.value) { return { buttons: { a: gamepad.value.buttons[0], b: gamepad.value.buttons[1], x: gamepad.value.buttons[2], y: gamepad.value.buttons[3] }, bumper: { left: gamepad.value.buttons[4], right: gamepad.value.buttons[5] }, triggers: { left: gamepad.value.buttons[6], right: gamepad.value.buttons[7] }, stick: { left: { horizontal: gamepad.value.axes[0], vertical: gamepad.value.axes[1], button: gamepad.value.buttons[10] }, right: { horizontal: gamepad.value.axes[2], vertical: gamepad.value.axes[3], button: gamepad.value.buttons[11] } }, dpad: { up: gamepad.value.buttons[12], down: gamepad.value.buttons[13], left: gamepad.value.buttons[14], right: gamepad.value.buttons[15] }, back: gamepad.value.buttons[8], start: gamepad.value.buttons[9] }; } return null; }); } function useGamepad(options = {}) { const { navigator = defaultNavigator } = options; const isSupported = navigator && "getGamepads" in navigator; const gamepads = vueDemi.ref([]); const onConnectedHook = shared.createEventHook(); const onDisconnectedHook = shared.createEventHook(); const stateFromGamepad = (gamepad) => { const hapticActuators = []; const vibrationActuator = "vibrationActuator" in gamepad ? gamepad.vibrationActuator : null; if (vibrationActuator) hapticActuators.push(vibrationActuator); if (gamepad.hapticActuators) hapticActuators.push(...gamepad.hapticActuators); return { id: gamepad.id, hapticActuators, index: gamepad.index, mapping: gamepad.mapping, connected: gamepad.connected, timestamp: gamepad.timestamp, axes: gamepad.axes.map((axes) => axes), buttons: gamepad.buttons.map((button) => ({ pressed: button.pressed, touched: button.touched, value: button.value })) }; }; const updateGamepadState = () => { const _gamepads = (navigator == null ? void 0 : navigator.getGamepads()) || []; for (let i = 0; i < _gamepads.length; ++i) { const gamepad = _gamepads[i]; if (gamepad) { const index = gamepads.value.findIndex(({ index: index2 }) => index2 === gamepad.index); if (index > -1) gamepads.value[index] = stateFromGamepad(gamepad); } } }; const { isActive, pause, resume } = core.useRafFn(updateGamepadState); const onGamepadConnected = (gamepad) => { if (!gamepads.value.some(({ index }) => index === gamepad.index)) { gamepads.value.push(stateFromGamepad(gamepad)); onConnectedHook.trigger(gamepad.index); } resume(); }; const onGamepadDisconnected = (gamepad) => { gamepads.value = gamepads.value.filter((x) => x.index !== gamepad.index); onDisconnectedHook.trigger(gamepad.index); }; core.useEventListener("gamepadconnected", (e) => onGamepadConnected(e.gamepad)); core.useEventListener("gamepaddisconnected", (e) => onGamepadDisconnected(e.gamepad)); shared.tryOnMounted(() => { const _gamepads = (navigator == null ? void 0 : navigator.getGamepads()) || []; if (_gamepads) { for (let i = 0; i < _gamepads.length; ++i) { const gamepad = _gamepads[i]; if (gamepad) onGamepadConnected(gamepad); } } }); pause(); return { isSupported, onConnected: onConnectedHook.on, onDisconnected: onDisconnectedHook.on, gamepads, pause, resume, isActive }; } function useGeolocation(options = {}) { const { enableHighAccuracy = true, maximumAge = 3e4, timeout = 27e3, navigator = defaultNavigator } = options; const isSupported = navigator && "geolocation" in navigator; const locatedAt = vueDemi.ref(null); const error = vueDemi.ref(null); const coords = vueDemi.ref({ accuracy: 0, latitude: Infinity, longitude: Infinity, altitude: null, altitudeAccuracy: null, heading: null, speed: null }); function updatePosition(position) { locatedAt.value = position.timestamp; coords.value = position.coords; error.value = null; } let watcher; if (isSupported) { watcher = navigator.geolocation.watchPosition(updatePosition, (err) => error.value = err, { enableHighAccuracy, maximumAge, timeout }); } shared.tryOnScopeDispose(() => { if (watcher && navigator) navigator.geolocation.clearWatch(watcher); }); return { isSupported, coords, locatedAt, error }; } const defaultEvents$1 = ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"]; const oneMinute = 6e4; function useIdle(timeout = oneMinute, options = {}) { const { initialState = false, listenForVisibilityChange = true, events = defaultEvents$1, window = defaultWindow, eventFilter = shared.throttleFilter(50) } = options; const idle = vueDemi.ref(initialState); const lastActive = vueDemi.ref(shared.timestamp()); let timer; const onEvent = shared.createFilterWrapper(eventFilter, () => { idle.value = false; lastActive.value = shared.timestamp(); clearTimeout(timer); timer = setTimeout(() => idle.value = true, timeout); }); if (window) { const document = window.document; for (const event of events) useEventListener(window, event, onEvent, { passive: true }); if (listenForVisibilityChange) { useEventListener(document, "visibilitychange", () => { if (!document.hidden) onEvent(); }); } } timer = setTimeout(() => idle.value = true, timeout); return { idle, lastActive }; } function useScroll(element, options = {}) { const { throttle = 0, idle = 200, onStop = shared.noop, onScroll = shared.noop, offset = { left: 0, right: 0, top: 0, bottom: 0 }, eventListenerOptions = { capture: false, passive: true } } = options; const x = vueDemi.ref(0); const y = vueDemi.ref(0); const isScrolling = vueDemi.ref(false); const arrivedState = vueDemi.reactive({ left: true, right: false, top: true, bottom: false }); const directions = vueDemi.reactive({ left: false, right: false, top: false, bottom: false }); if (element) { const onScrollEnd = shared.useDebounceFn((e) => { isScrolling.value = false; directions.left = false; directions.right = false; directions.top = false; directions.bottom = false; onStop(e); }, throttle + idle); const onScrollHandler = (e) => { const eventTarget = e.target === document ? e.target.documentElement : e.target; const scrollLeft = eventTarget.scrollLeft; directions.left = scrollLeft < x.value; directions.right = scrollLeft > x.value; arrivedState.left = scrollLeft <= 0 + (offset.left || 0); arrivedState.right = scrollLeft + eventTarget.clientWidth >= eventTarget.scrollWidth - (offset.right || 0); x.value = scrollLeft; const scrollTop = eventTarget.scrollTop; directions.top = scrollTop < y.value; directions.bottom = scrollTop > y.value; arrivedState.top = scrollTop <= 0 + (offset.top || 0); arrivedState.bottom = scrollTop + eventTarget.clientHeight >= eventTarget.scrollHeight - (offset.bottom || 0); y.value = scrollTop; isScrolling.value = true; onScrollEnd(e); onScroll(e); }; useEventListener(element, "scroll", throttle ? shared.useThrottleFn(onScrollHandler, throttle) : onScrollHandler, eventListenerOptions); } return { x, y, isScrolling, arrivedState, directions }; } var __defProp$7 = Object.defineProperty; var __defProps$2 = Object.defineProperties; var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols; var __hasOwnProp$8 = Object.prototype.hasOwnProperty; var __propIsEnum$8 = Object.prototype.propertyIsEnumerable; var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$7 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$8.call(b, prop)) __defNormalProp$7(a, prop, b[prop]); if (__getOwnPropSymbols$8) for (var prop of __getOwnPropSymbols$8(b)) { if (__propIsEnum$8.call(b, prop)) __defNormalProp$7(a, prop, b[prop]); } return a; }; var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); function useInfiniteScroll(element, onLoadMore, options = {}) { var _a; const state = vueDemi.reactive(useScroll(element, __spreadProps$2(__spreadValues$7({}, options), { offset: __spreadValues$7({ bottom: (_a = options.distance) != null ? _a : 0 }, options.offset) }))); vueDemi.watch(() => state.arrivedState.bottom, (v) => { if (v) onLoadMore(state); }); } function useIntersectionObserver(target, callback, options = {}) { const { root, rootMargin = "0px", threshold = 0.1, window = defaultWindow } = options; const isSupported = window && "IntersectionObserver" in window; let cleanup = shared.noop; const stopWatch = isSupported ? vueDemi.watch(() => ({ el: unrefElement(target), root: unrefElement(root) }), ({ el, root: root2 }) => { cleanup(); if (!el) return; const observer = new IntersectionObserver(callback, { root: root2, rootMargin, threshold }); observer.observe(el); cleanup = () => { observer.disconnect(); cleanup = shared.noop; }; }, { immediate: true, flush: "post" }) : shared.noop; const stop = () => { cleanup(); stopWatch(); }; shared.tryOnScopeDispose(stop); return { isSupported, stop }; } const defaultEvents = ["mousedown", "mouseup", "keydown", "keyup"]; function useKeyModifier(modifier, options = {}) { const { events = defaultEvents, document = defaultDocument, initial = null } = options; const state = vueDemi.ref(initial); if (document) { events.forEach((listenerEvent) => { useEventListener(document, listenerEvent, (evt) => { if (typeof evt.getModifierState === "function") state.value = evt.getModifierState(modifier); }); }); } return state; } function useLocalStorage(key, initialValue, options = {}) { const { window = defaultWindow } = options; return useStorage(key, initialValue, window == null ? void 0 : window.localStorage, options); } const DefaultMagicKeysAliasMap = { ctrl: "control", command: "meta", cmd: "meta", option: "alt", up: "arrowup", down: "arrowdown", left: "arrowleft", right: "arrowright" }; function useMagicKeys(options = {}) { const { reactive: useReactive = false, target = defaultWindow, aliasMap = DefaultMagicKeysAliasMap, passive = true, onEventFired = shared.noop } = options; const current = vueDemi.reactive(/* @__PURE__ */ new Set()); const obj = { toJSON() { return {}; }, current }; const refs = useReactive ? vueDemi.reactive(obj) : obj; const metaDeps = /* @__PURE__ */ new Set(); function setRefs(key, value) { if (key in refs) { if (useReactive) refs[key] = value; else refs[key].value = value; } } function updateRefs(e, value) { var _a, _b; const key = (_a = e.key) == null ? void 0 : _a.toLowerCase(); const code = (_b = e.code) == null ? void 0 : _b.toLowerCase(); const values = [code, key].filter(Boolean); if (code) { if (value) current.add(e.code); else current.delete(e.code); } for (const key2 of values) setRefs(key2, value); if (key === "meta" && !value) { metaDeps.forEach((key2) => { current.delete(key2); setRefs(key2, false); }); metaDeps.clear(); } else if (e.getModifierState("Meta") && value) { [...current, ...values].forEach((key2) => metaDeps.add(key2)); } } if (target) { useEventListener(target, "keydown", (e) => { updateRefs(e, true); return onEventFired(e); }, { passive }); useEventListener(target, "keyup", (e) => { updateRefs(e, false); return onEventFired(e); }, { passive }); } const proxy = new Proxy(refs, { get(target2, prop, rec) { if (typeof prop !== "string") return Reflect.get(target2, prop, rec); prop = prop.toLowerCase(); if (prop in aliasMap) prop = aliasMap[prop]; if (!(prop in refs)) { if (/[+_-]/.test(prop)) { const keys = prop.split(/[+_-]/g).map((i) => i.trim()); refs[prop] = vueDemi.computed(() => keys.every((key) => vueDemi.unref(proxy[key]))); } else { refs[prop] = vueDemi.ref(false); } } const r = Reflect.get(target2, prop, rec); return useReactive ? vueDemi.unref(r) : r; } }); return proxy; } var __defProp$6 = Object.defineProperty; var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols; var __hasOwnProp$7 = Object.prototype.hasOwnProperty; var __propIsEnum$7 = Object.prototype.propertyIsEnumerable; var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$6 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$7.call(b, prop)) __defNormalProp$6(a, prop, b[prop]); if (__getOwnPropSymbols$7) for (var prop of __getOwnPropSymbols$7(b)) { if (__propIsEnum$7.call(b, prop)) __defNormalProp$6(a, prop, b[prop]); } return a; }; function usingElRef(source, cb) { if (vueDemi.unref(source)) cb(vueDemi.unref(source)); } function timeRangeToArray(timeRanges) { let ranges = []; for (let i = 0; i < timeRanges.length; ++i) ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]]; return ranges; } function tracksToArray(tracks) { return Array.from(tracks).map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id) => ({ id, label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType })); } const defaultOptions = { src: "", tracks: [] }; function useMediaControls(target, options = {}) { options = __spreadValues$6(__spreadValues$6({}, defaultOptions), options); const { document = defaultDocument } = options; const currentTime = vueDemi.ref(0); const duration = vueDemi.ref(0); const seeking = vueDemi.ref(false); const volume = vueDemi.ref(1); const waiting = vueDemi.ref(false); const ended = vueDemi.ref(false); const playing = vueDemi.ref(false); const rate = vueDemi.ref(1); const stalled = vueDemi.ref(false); const buffered = vueDemi.ref([]); const tracks = vueDemi.ref([]); const selectedTrack = vueDemi.ref(-1); const isPictureInPicture = vueDemi.ref(false); const muted = vueDemi.ref(false); const supportsPictureInPicture = document && "pictureInPictureEnabled" in document; const sourceErrorEvent = shared.createEventHook(); const disableTrack = (track) => { usingElRef(target, (el) => { if (track) { const id = shared.isNumber(track) ? track : track.id; el.textTracks[id].mode = "disabled"; } else { for (let i = 0; i < el.textTracks.length; ++i) el.textTracks[i].mode = "disabled"; } selectedTrack.value = -1; }); }; const enableTrack = (track, disableTracks = true) => { usingElRef(target, (el) => { const id = shared.isNumber(track) ? track : track.id; if (disableTracks) disableTrack(); el.textTracks[id].mode = "showing"; selectedTrack.value = id; }); }; const togglePictureInPicture = () => { return new Promise((resolve, reject) => { usingElRef(target, async (el) => { if (supportsPictureInPicture) { if (!isPictureInPicture.value) { el.requestPictureInPicture().then(resolve).catch(reject); } else { document.exitPictureInPicture().then(resolve).catch(reject); } } }); }); }; vueDemi.watchEffect(() => { if (!document) return; const el = vueDemi.unref(target); if (!el) return; const src = vueDemi.unref(options.src); let sources = []; if (!src) return; if (shared.isString(src)) sources = [{ src }]; else if (Array.isArray(src)) sources = src; else if (shared.isObject(src)) sources = [src]; el.querySelectorAll("source").forEach((e) => { e.removeEventListener("error", sourceErrorEvent.trigger); e.remove(); }); sources.forEach(({ src: src2, type }) => { const source = document.createElement("source"); source.setAttribute("src", src2); source.setAttribute("type", type || ""); source.addEventListener("error", sourceErrorEvent.trigger); el.appendChild(source); }); el.load(); }); shared.tryOnScopeDispose(() => { const el = vueDemi.unref(target); if (!el) return; el.querySelectorAll("source").forEach((e) => e.removeEventListener("error", sourceErrorEvent.trigger)); }); vueDemi.watch(volume, (vol) => { const el = vueDemi.unref(target); if (!el) return; el.volume = vol; }); vueDemi.watch(muted, (mute) => { const el = vueDemi.unref(target); if (!el) return; el.muted = mute; }); vueDemi.watch(rate, (rate2) => { const el = vueDemi.unref(target); if (!el) return; el.playbackRate = rate2; }); vueDemi.watchEffect(() => { if (!document) return; const textTracks = vueDemi.unref(options.tracks); const el = vueDemi.unref(target); if (!textTracks || !textTracks.length || !el) return; el.querySelectorAll("track").forEach((e) => e.remove()); textTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i) => { const track = document.createElement("track"); track.default = isDefault || false; track.kind = kind; track.label = label; track.src = src; track.srclang = srcLang; if (track.default) selectedTrack.value = i; el.appendChild(track); }); }); const { ignoreUpdates: ignoreCurrentTimeUpdates } = shared.watchIgnorable(currentTime, (time) => { const el = vueDemi.unref(target); if (!el) return; el.currentTime = time; }); const { ignoreUpdates: ignorePlayingUpdates } = shared.watchIgnorable(playing, (isPlaying) => { const el = vueDemi.unref(target); if (!el) return; isPlaying ? el.play() : el.pause(); }); useEventListener(target, "timeupdate", () => ignoreCurrentTimeUpdates(() => currentTime.value = vueDemi.unref(target).currentTime)); useEventListener(target, "durationchange", () => duration.value = vueDemi.unref(target).duration); useEventListener(target, "progress", () => buffered.value = timeRangeToArray(vueDemi.unref(target).buffered)); useEventListener(target, "seeking", () => seeking.value = true); useEventListener(target, "seeked", () => seeking.value = false); useEventListener(target, "waiting", () => waiting.value = true); useEventListener(target, "playing", () => waiting.value = false); useEventListener(target, "ratechange", () => rate.value = vueDemi.unref(target).playbackRate); useEventListener(target, "stalled", () => stalled.value = true); useEventListener(target, "ended", () => ended.value = true); useEventListener(target, "pause", () => ignorePlayingUpdates(() => playing.value = false)); useEventListener(target, "play", () => ignorePlayingUpdates(() => playing.value = true)); useEventListener(target, "enterpictureinpicture", () => isPictureInPicture.value = true); useEventListener(target, "leavepictureinpicture", () => isPictureInPicture.value = false); useEventListener(target, "volumechange", () => { const el = vueDemi.unref(target); if (!el) return; volume.value = el.volume; muted.value = el.muted; }); const listeners = []; const stop = vueDemi.watch([target], () => { const el = vueDemi.unref(target); if (!el) return; stop(); listeners[0] = useEventListener(el.textTracks, "addtrack", () => tracks.value = tracksToArray(el.textTracks)); listeners[1] = useEventListener(el.textTracks, "removetrack", () => tracks.value = tracksToArray(el.textTracks)); listeners[2] = useEventListener(el.textTracks, "change", () => tracks.value = tracksToArray(el.textTracks)); }); shared.tryOnScopeDispose(() => listeners.forEach((listener) => listener())); return { currentTime, duration, waiting, seeking, ended, stalled, buffered, playing, rate, volume, muted, tracks, selectedTrack, enableTrack, disableTrack, supportsPictureInPicture, togglePictureInPicture, isPictureInPicture, onSourceError: sourceErrorEvent.on }; } const getMapVue2Compat = () => { const data = vueDemi.reactive({}); return { get: (key) => data[key], set: (key, value) => vueDemi.set(data, key, value), has: (key) => Object.prototype.hasOwnProperty.call(data, key), delete: (key) => vueDemi.del(data, key), clear: () => { Object.keys(data).forEach((key) => { vueDemi.del(data, key); }); } }; }; function useMemoize(resolver, options) { const initCache = () => { if (options == null ? void 0 : options.cache) return vueDemi.reactive(options.cache); if (vueDemi.isVue2) return getMapVue2Compat(); return vueDemi.reactive(/* @__PURE__ */ new Map()); }; const cache = initCache(); const generateKey = (...args) => (options == null ? void 0 : options.getKey) ? options.getKey(...args) : JSON.stringify(args); const _loadData = (key, ...args) => { cache.set(key, resolver(...args)); return cache.get(key); }; const loadData = (...args) => _loadData(generateKey(...args), ...args); const deleteData = (...args) => { cache.delete(generateKey(...args)); }; const clearData = () => { cache.clear(); }; const memoized = (...args) => { const key = generateKey(...args); if (cache.has(key)) return cache.get(key); return _loadData(key, ...args); }; memoized.load = loadData; memoized.delete = deleteData; memoized.clear = clearData; memoized.generateKey = generateKey; memoized.cache = cache; return memoized; } function useMemory(options = {}) { const memory = vueDemi.ref(); const isSupported = typeof performance !== "undefined" && "memory" in performance; if (isSupported) { const { interval = 1e3 } = options; shared.useIntervalFn(() => { memory.value = performance.memory; }, interval, { immediate: options.immediate, immediateCallback: options.immediateCallback }); } return { isSupported, memory }; } function useMounted() { const isMounted = vueDemi.ref(false); vueDemi.onMounted(() => { isMounted.value = true; }); return isMounted; } function useMouse(options = {}) { const { type = "page", touch = true, resetOnTouchEnds = false, initialValue = { x: 0, y: 0 }, window = defaultWindow, eventFilter } = options; const x = vueDemi.ref(initialValue.x); const y = vueDemi.ref(initialValue.y); const sourceType = vueDemi.ref(null); const mouseHandler = (event) => { if (type === "page") { x.value = event.pageX; y.value = event.pageY; } else if (type === "client") { x.value = event.clientX; y.value = event.clientY; } sourceType.value = "mouse"; }; const reset = () => { x.value = initialValue.x; y.value = initialValue.y; }; const touchHandler = (event) => { if (event.touches.length > 0) { const touch2 = event.touches[0]; if (type === "page") { x.value = touch2.pageX; y.value = touch2.pageY; } else if (type === "client") { x.value = touch2.clientX; y.value = touch2.clientY; } sourceType.value = "touch"; } }; const mouseHandlerWrapper = (event) => { return eventFilter === void 0 ? mouseHandler(event) : eventFilter(() => mouseHandler(event), {}); }; const touchHandlerWrapper = (event) => { return eventFilter === void 0 ? touchHandler(event) : eventFilter(() => touchHandler(event), {}); }; if (window) { useEventListener(window, "mousemove", mouseHandlerWrapper, { passive: true }); useEventListener(window, "dragover", mouseHandlerWrapper, { passive: true }); if (touch) { useEventListener(window, "touchstart", touchHandlerWrapper, { passive: true }); useEventListener(window, "touchmove", touchHandlerWrapper, { passive: true }); if (resetOnTouchEnds) useEventListener(window, "touchend", reset, { passive: true }); } } return { x, y, sourceType }; } function useMouseInElement(target, options = {}) { const { handleOutside = true, window = defaultWindow } = options; const { x, y, sourceType } = useMouse(options); const targetRef = vueDemi.ref(target != null ? target : window == null ? void 0 : window.document.body); const elementX = vueDemi.ref(0); const elementY = vueDemi.ref(0); const elementPositionX = vueDemi.ref(0); const elementPositionY = vueDemi.ref(0); const elementHeight = vueDemi.ref(0); const elementWidth = vueDemi.ref(0); const isOutside = vueDemi.ref(false); let stop = () => { }; if (window) { stop = vueDemi.watch([targetRef, x, y], () => { const el = unrefElement(targetRef); if (!el) return; const { left, top, width, height } = el.getBoundingClientRect(); elementPositionX.value = left + window.pageXOffset; elementPositionY.value = top + window.pageYOffset; elementHeight.value = height; elementWidth.value = width; const elX = x.value - elementPositionX.value; const elY = y.value - elementPositionY.value; isOutside.value = elX < 0 || elY < 0 || elX > elementWidth.value || elY > elementHeight.value; if (handleOutside || !isOutside.value) { elementX.value = elX; elementY.value = elY; } }, { immediate: true }); } return { x, y, sourceType, elementX, elementY, elementPositionX, elementPositionY, elementHeight, elementWidth, isOutside, stop }; } function useMousePressed(options = {}) { const { touch = true, drag = true, initialValue = false, window = defaultWindow } = options; const pressed = vueDemi.ref(initialValue); const sourceType = vueDemi.ref(null); if (!window) { return { pressed, sourceType }; } const onPressed = (srcType) => () => { pressed.value = true; sourceType.value = srcType; }; const onReleased = () => { pressed.value = false; sourceType.value = null; }; const target = vueDemi.computed(() => unrefElement(options.target) || window); useEventListener(target, "mousedown", onPressed("mouse"), { passive: true }); useEventListener(window, "mouseleave", onReleased, { passive: true }); useEventListener(window, "mouseup", onReleased, { passive: true }); if (drag) { useEventListener(target, "dragstart", onPressed("mouse"), { passive: true }); useEventListener(window, "drop", onReleased, { passive: true }); useEventListener(window, "dragend", onReleased, { passive: true }); } if (touch) { useEventListener(target, "touchstart", onPressed("touch"), { passive: true }); useEventListener(window, "touchend", onReleased, { passive: true }); useEventListener(window, "touchcancel", onReleased, { passive: true }); } return { pressed, sourceType }; } var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols; var __hasOwnProp$6 = Object.prototype.hasOwnProperty; var __propIsEnum$6 = Object.prototype.propertyIsEnumerable; var __objRest$1 = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols$6) for (var prop of __getOwnPropSymbols$6(source)) { if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop)) target[prop] = source[prop]; } return target; }; function useMutationObserver(target, callback, options = {}) { const _a = options, { window = defaultWindow } = _a, mutationOptions = __objRest$1(_a, ["window"]); let observer; const isSupported = window && "IntersectionObserver" in window; const cleanup = () => { if (observer) { observer.disconnect(); observer = void 0; } }; const stopWatch = vueDemi.watch(() => unrefElement(target), (el) => { cleanup(); if (isSupported && window && el) { observer = new MutationObserver(callback); observer.observe(el, mutationOptions); } }, { immediate: true }); const stop = () => { cleanup(); stopWatch(); }; shared.tryOnScopeDispose(stop); return { isSupported, stop }; } const useNavigatorLanguage = (options = {}) => { const { window = defaultWindow } = options; const navigator = window == null ? void 0 : window.navigator; const isSupported = Boolean(navigator && "language" in navigator); const language = vueDemi.ref(navigator == null ? void 0 : navigator.language); useEventListener(window, "languagechange", () => { if (navigator) language.value = navigator.language; }); return { isSupported, language }; }; function useNetwork(options = {}) { const { window = defaultWindow } = options; const navigator = window == null ? void 0 : window.navigator; const isSupported = Boolean(navigator && "connection" in navigator); const isOnline = vueDemi.ref(true); const saveData = vueDemi.ref(false); const offlineAt = vueDemi.ref(void 0); const downlink = vueDemi.ref(void 0); const downlinkMax = vueDemi.ref(void 0); const rtt = vueDemi.ref(void 0); const effectiveType = vueDemi.ref(void 0); const type = vueDemi.ref("unknown"); const connection = isSupported && navigator.connection; function updateNetworkInformation() { if (!navigator) return; isOnline.value = navigator.onLine; offlineAt.value = isOnline.value ? void 0 : Date.now(); if (connection) { downlink.value = connection.downlink; downlinkMax.value = connection.downlinkMax; effectiveType.value = connection.effectiveType; rtt.value = connection.rtt; saveData.value = connection.saveData; type.value = connection.type; } } if (window) { useEventListener(window, "offline", () => { isOnline.value = false; offlineAt.value = Date.now(); }); useEventListener(window, "online", () => { isOnline.value = true; }); } if (connection) useEventListener(connection, "change", updateNetworkInformation, false); updateNetworkInformation(); return { isSupported, isOnline, saveData, offlineAt, downlink, downlinkMax, effectiveType, rtt, type }; } var __defProp$5 = Object.defineProperty; var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols; var __hasOwnProp$5 = Object.prototype.hasOwnProperty; var __propIsEnum$5 = Object.prototype.propertyIsEnumerable; var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$5 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$5.call(b, prop)) __defNormalProp$5(a, prop, b[prop]); if (__getOwnPropSymbols$5) for (var prop of __getOwnPropSymbols$5(b)) { if (__propIsEnum$5.call(b, prop)) __defNormalProp$5(a, prop, b[prop]); } return a; }; function useNow(options = {}) { const { controls: exposeControls = false, interval = "requestAnimationFrame" } = options; const now = vueDemi.ref(new Date()); const update = () => now.value = new Date(); const controls = interval === "requestAnimationFrame" ? useRafFn(update, { immediate: true }) : shared.useIntervalFn(update, interval, { immediate: true }); if (exposeControls) { return __spreadValues$5({ now }, controls); } else { return now; } } function useOffsetPagination(options) { const { total = Infinity, pageSize = 10, page = 1, onPageChange = shared.noop, onPageSizeChange = shared.noop, onPageCountChange = shared.noop } = options; const currentPageSize = useClamp(pageSize, 1, Infinity); const pageCount = vueDemi.computed(() => Math.ceil(vueDemi.unref(total) / vueDemi.unref(currentPageSize))); const currentPage = useClamp(page, 1, pageCount); const isFirstPage = vueDemi.computed(() => currentPage.value === 1); const isLastPage = vueDemi.computed(() => currentPage.value === pageCount.value); if (vueDemi.isRef(page)) shared.syncRef(page, currentPage); if (vueDemi.isRef(pageSize)) shared.syncRef(pageSize, currentPageSize); function prev() { currentPage.value--; } function next() { currentPage.value++; } const returnValue = { currentPage, currentPageSize, pageCount, isFirstPage, isLastPage, prev, next }; vueDemi.watch(currentPage, () => { onPageChange(vueDemi.reactive(returnValue)); }); vueDemi.watch(currentPageSize, () => { onPageSizeChange(vueDemi.reactive(returnValue)); }); vueDemi.watch(pageCount, () => { onPageCountChange(vueDemi.reactive(returnValue)); }); return returnValue; } function useOnline(options = {}) { const { isOnline } = useNetwork(options); return isOnline; } function usePageLeave(options = {}) { const { window = defaultWindow } = options; const isLeft = vueDemi.ref(false); const handler = (event) => { if (!window) return; event = event || window.event; const from = event.relatedTarget || event.toElement; isLeft.value = !from; }; if (window) { useEventListener(window, "mouseout", handler, { passive: true }); useEventListener(window.document, "mouseleave", handler, { passive: true }); useEventListener(window.document, "mouseenter", handler, { passive: true }); } return isLeft; } function useParallax(target, options = {}) { const { deviceOrientationTiltAdjust = (i) => i, deviceOrientationRollAdjust = (i) => i, mouseTiltAdjust = (i) => i, mouseRollAdjust = (i) => i, window = defaultWindow } = options; const orientation = vueDemi.reactive(useDeviceOrientation({ window })); const { elementX: x, elementY: y, elementWidth: width, elementHeight: height } = useMouseInElement(target, { handleOutside: false, window }); const source = vueDemi.computed(() => { if (orientation.isSupported && (orientation.alpha != null && orientation.alpha !== 0 || orientation.gamma != null && orientation.gamma !== 0)) return "deviceOrientation"; return "mouse"; }); const roll = vueDemi.computed(() => { if (source.value === "deviceOrientation") { const value = -orientation.beta / 90; return deviceOrientationRollAdjust(value); } else { const value = -(y.value - height.value / 2) / height.value; return mouseRollAdjust(value); } }); const tilt = vueDemi.computed(() => { if (source.value === "deviceOrientation") { const value = orientation.gamma / 90; return deviceOrientationTiltAdjust(value); } else { const value = (x.value - width.value / 2) / width.value; return mouseTiltAdjust(value); } }); return { roll, tilt, source }; } var __defProp$4 = Object.defineProperty; var __defProps$1 = Object.defineProperties; var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; var __hasOwnProp$4 = Object.prototype.hasOwnProperty; var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$4 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$4.call(b, prop)) __defNormalProp$4(a, prop, b[prop]); if (__getOwnPropSymbols$4) for (var prop of __getOwnPropSymbols$4(b)) { if (__propIsEnum$4.call(b, prop)) __defNormalProp$4(a, prop, b[prop]); } return a; }; var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); const defaultState = { x: 0, y: 0, pointerId: 0, pressure: 0, tiltX: 0, tiltY: 0, width: 0, height: 0, twist: 0, pointerType: null }; const keys = /* @__PURE__ */ Object.keys(defaultState); function usePointer(options = {}) { const { target = defaultWindow } = options; const isInside = vueDemi.ref(false); const state = vueDemi.ref(options.initialValue || {}); Object.assign(state.value, defaultState, state.value); const handler = (event) => { isInside.value = true; if (options.pointerTypes && !options.pointerTypes.includes(event.pointerType)) return; state.value = shared.objectPick(event, keys, false); }; if (target) { useEventListener(target, "pointerdown", handler, { passive: true }); useEventListener(target, "pointermove", handler, { passive: true }); useEventListener(target, "pointerleave", () => isInside.value = false, { passive: true }); } return __spreadProps$1(__spreadValues$4({}, shared.toRefs(state)), { isInside }); } var SwipeDirection = /* @__PURE__ */ ((SwipeDirection2) => { SwipeDirection2["UP"] = "UP"; SwipeDirection2["RIGHT"] = "RIGHT"; SwipeDirection2["DOWN"] = "DOWN"; SwipeDirection2["LEFT"] = "LEFT"; SwipeDirection2["NONE"] = "NONE"; return SwipeDirection2; })(SwipeDirection || {}); function useSwipe(target, options = {}) { const { threshold = 50, onSwipe, onSwipeEnd, onSwipeStart, passive = true, window = defaultWindow } = options; const coordsStart = vueDemi.reactive({ x: 0, y: 0 }); const coordsEnd = vueDemi.reactive({ x: 0, y: 0 }); const diffX = vueDemi.computed(() => coordsStart.x - coordsEnd.x); const diffY = vueDemi.computed(() => coordsStart.y - coordsEnd.y); const { max, abs } = Math; const isThresholdExceeded = vueDemi.computed(() => max(abs(diffX.value), abs(diffY.value)) >= threshold); const isSwiping = vueDemi.ref(false); const direction = vueDemi.computed(() => { if (!isThresholdExceeded.value) return "NONE" /* NONE */; if (abs(diffX.value) > abs(diffY.value)) { return diffX.value > 0 ? "LEFT" /* LEFT */ : "RIGHT" /* RIGHT */; } else { return diffY.value > 0 ? "UP" /* UP */ : "DOWN" /* DOWN */; } }); const getTouchEventCoords = (e) => [e.touches[0].clientX, e.touches[0].clientY]; const updateCoordsStart = (x, y) => { coordsStart.x = x; coordsStart.y = y; }; const updateCoordsEnd = (x, y) => { coordsEnd.x = x; coordsEnd.y = y; }; let listenerOptions; const isPassiveEventSupported = checkPassiveEventSupport(window == null ? void 0 : window.document); if (!passive) listenerOptions = isPassiveEventSupported ? { passive: false, capture: true } : { capture: true }; else listenerOptions = isPassiveEventSupported ? { passive: true } : { capture: false }; const onTouchEnd = (e) => { if (isSwiping.value) onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value); isSwiping.value = false; }; const stops = [ useEventListener(target, "touchstart", (e) => { if (listenerOptions.capture && !listenerOptions.passive) e.preventDefault(); const [x, y] = getTouchEventCoords(e); updateCoordsStart(x, y); updateCoordsEnd(x, y); onSwipeStart == null ? void 0 : onSwipeStart(e); }, listenerOptions), useEventListener(target, "touchmove", (e) => { const [x, y] = getTouchEventCoords(e); updateCoordsEnd(x, y); if (!isSwiping.value && isThresholdExceeded.value) isSwiping.value = true; if (isSwiping.value) onSwipe == null ? void 0 : onSwipe(e); }, listenerOptions), useEventListener(target, "touchend", onTouchEnd, listenerOptions), useEventListener(target, "touchcancel", onTouchEnd, listenerOptions) ]; const stop = () => stops.forEach((s) => s()); return { isPassiveEventSupported, isSwiping, direction, coordsStart, coordsEnd, lengthX: diffX, lengthY: diffY, stop }; } function checkPassiveEventSupport(document) { if (!document) return false; let supportsPassive = false; const optionsBlock = { get passive() { supportsPassive = true; return false; } }; document.addEventListener("x", shared.noop, optionsBlock); document.removeEventListener("x", shared.noop); return supportsPassive; } function usePointerSwipe(target, options = {}) { const targetRef = vueDemi.ref(target); const { threshold = 50, onSwipe, onSwipeEnd, onSwipeStart } = options; const posStart = vueDemi.reactive({ x: 0, y: 0 }); const updatePosStart = (x, y) => { posStart.x = x; posStart.y = y; }; const posEnd = vueDemi.reactive({ x: 0, y: 0 }); const updatePosEnd = (x, y) => { posEnd.x = x; posEnd.y = y; }; const distanceX = vueDemi.computed(() => posStart.x - posEnd.x); const distanceY = vueDemi.computed(() => posStart.y - posEnd.y); const { max, abs } = Math; const isThresholdExceeded = vueDemi.computed(() => max(abs(distanceX.value), abs(distanceY.value)) >= threshold); const isSwiping = vueDemi.ref(false); const isPointerDown = vueDemi.ref(false); const direction = vueDemi.computed(() => { if (!isThresholdExceeded.value) return SwipeDirection.NONE; if (abs(distanceX.value) > abs(distanceY.value)) { return distanceX.value > 0 ? SwipeDirection.LEFT : SwipeDirection.RIGHT; } else { return distanceY.value > 0 ? SwipeDirection.UP : SwipeDirection.DOWN; } }); const filterEvent = (e) => { if (options.pointerTypes) return options.pointerTypes.includes(e.pointerType); return true; }; const stops = [ useEventListener(target, "pointerdown", (e) => { var _a, _b; if (!filterEvent(e)) return; isPointerDown.value = true; (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null ? void 0 : _b.setProperty("touch-action", "none"); const eventTarget = e.target; eventTarget == null ? void 0 : eventTarget.setPointerCapture(e.pointerId); const { clientX: x, clientY: y } = e; updatePosStart(x, y); updatePosEnd(x, y); onSwipeStart == null ? void 0 : onSwipeStart(e); }), useEventListener(target, "pointermove", (e) => { if (!filterEvent(e)) return; if (!isPointerDown.value) return; const { clientX: x, clientY: y } = e; updatePosEnd(x, y); if (!isSwiping.value && isThresholdExceeded.value) isSwiping.value = true; if (isSwiping.value) onSwipe == null ? void 0 : onSwipe(e); }), useEventListener(target, "pointerup", (e) => { var _a, _b; if (!filterEvent(e)) return; if (isSwiping.value) onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value); isPointerDown.value = false; isSwiping.value = false; (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null ? void 0 : _b.setProperty("touch-action", "initial"); }) ]; const stop = () => stops.forEach((s) => s()); return { isSwiping: vueDemi.readonly(isSwiping), direction: vueDemi.readonly(direction), posStart: vueDemi.readonly(posStart), posEnd: vueDemi.readonly(posEnd), distanceX, distanceY, stop }; } function usePreferredColorScheme(options) { const isLight = useMediaQuery("(prefers-color-scheme: light)", options); const isDark = useMediaQuery("(prefers-color-scheme: dark)", options); return vueDemi.computed(() => { if (isDark.value) return "dark"; if (isLight.value) return "light"; return "no-preference"; }); } function usePreferredLanguages(options = {}) { const { window = defaultWindow } = options; if (!window) return vueDemi.ref(["en"]); const navigator = window.navigator; const value = vueDemi.ref(navigator.languages); useEventListener(window, "languagechange", () => { value.value = navigator.languages; }); return value; } const topVarName = "--vueuse-safe-area-top"; const rightVarName = "--vueuse-safe-area-right"; const bottomVarName = "--vueuse-safe-area-bottom"; const leftVarName = "--vueuse-safe-area-left"; function useScreenSafeArea() { const top = vueDemi.ref(""); const right = vueDemi.ref(""); const bottom = vueDemi.ref(""); const left = vueDemi.ref(""); if (shared.isClient) { const topCssVar = useCssVar(topVarName); const rightCssVar = useCssVar(rightVarName); const bottomCssVar = useCssVar(bottomVarName); const leftCssVar = useCssVar(leftVarName); topCssVar.value = "env(safe-area-inset-top, 0px)"; rightCssVar.value = "env(safe-area-inset-right, 0px)"; bottomCssVar.value = "env(safe-area-inset-bottom, 0px)"; leftCssVar.value = "env(safe-area-inset-left, 0px)"; update(); useEventListener("resize", shared.useDebounceFn(update)); } function update() { top.value = getValue(topVarName); right.value = getValue(rightVarName); bottom.value = getValue(bottomVarName); left.value = getValue(leftVarName); } return { top, right, bottom, left, update }; } function getValue(position) { return getComputedStyle(document.documentElement).getPropertyValue(position); } function useScriptTag(src, onLoaded = shared.noop, options = {}) { const { immediate = true, manual = false, type = "text/javascript", async = true, crossOrigin, referrerPolicy, noModule, defer, document = defaultDocument, attrs = {} } = options; const scriptTag = vueDemi.ref(null); let _promise = null; const loadScript = (waitForScriptLoad) => new Promise((resolve, reject) => { const resolveWithElement = (el2) => { scriptTag.value = el2; resolve(el2); return el2; }; if (!document) { resolve(false); return; } let shouldAppend = false; let el = document.querySelector(`script[src="${src}"]`); if (!el) { el = document.createElement("script"); el.type = type; el.async = async; el.src = vueDemi.unref(src); if (defer) el.defer = defer; if (crossOrigin) el.crossOrigin = crossOrigin; if (noModule) el.noModule = noModule; if (referrerPolicy) el.referrerPolicy = referrerPolicy; for (const attr in attrs) el[attr] = attrs[attr]; shouldAppend = true; } else if (el.hasAttribute("data-loaded")) { resolveWithElement(el); } el.addEventListener("error", (event) => reject(event)); el.addEventListener("abort", (event) => reject(event)); el.addEventListener("load", () => { el.setAttribute("data-loaded", "true"); onLoaded(el); resolveWithElement(el); }); if (shouldAppend) el = document.head.appendChild(el); if (!waitForScriptLoad) resolveWithElement(el); }); const load = (waitForScriptLoad = true) => { if (!_promise) _promise = loadScript(waitForScriptLoad); return _promise; }; const unload = () => { if (!document) return; _promise = null; if (scriptTag.value) scriptTag.value = null; const el = document.querySelector(`script[src="${src}"]`); if (el) document.head.removeChild(el); }; if (immediate && !manual) shared.tryOnMounted(load); if (!manual) shared.tryOnUnmounted(unload); return { scriptTag, load, unload }; } var _a, _b; function preventDefault(rawEvent) { const e = rawEvent || window.event; if (e.touches.length > 1) return true; if (e.preventDefault) e.preventDefault(); return false; } const isIOS = shared.isClient && (window == null ? void 0 : window.navigator) && ((_a = window == null ? void 0 : window.navigator) == null ? void 0 : _a.platform) && /iP(ad|hone|od)/.test((_b = window == null ? void 0 : window.navigator) == null ? void 0 : _b.platform); function useScrollLock(element, initialState = false) { const isLocked = vueDemi.ref(initialState); let touchMoveListener = null; let initialOverflow; vueDemi.watch(() => vueDemi.unref(element), (el) => { if (el) { const ele = el; initialOverflow = ele.style.overflow; if (isLocked.value) ele.style.overflow = "hidden"; } }, { immediate: true }); const lock = () => { const ele = vueDemi.unref(element); if (!ele || isLocked.value) return; if (isIOS) { touchMoveListener = useEventListener(document, "touchmove", preventDefault, { passive: false }); } ele.style.overflow = "hidden"; isLocked.value = true; }; const unlock = () => { const ele = vueDemi.unref(element); if (!ele || !isLocked.value) return; isIOS && (touchMoveListener == null ? void 0 : touchMoveListener()); ele.style.overflow = initialOverflow; isLocked.value = false; }; return vueDemi.computed({ get() { return isLocked.value; }, set(v) { if (v) lock(); else unlock(); } }); } function useSessionStorage(key, initialValue, options = {}) { const { window = defaultWindow } = options; return useStorage(key, initialValue, window == null ? void 0 : window.sessionStorage, options); } var __defProp$3 = Object.defineProperty; var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; var __hasOwnProp$3 = Object.prototype.hasOwnProperty; var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$3 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$3.call(b, prop)) __defNormalProp$3(a, prop, b[prop]); if (__getOwnPropSymbols$3) for (var prop of __getOwnPropSymbols$3(b)) { if (__propIsEnum$3.call(b, prop)) __defNormalProp$3(a, prop, b[prop]); } return a; }; function useShare(shareOptions = {}, options = {}) { const { navigator = defaultNavigator } = options; const _navigator = navigator; const isSupported = _navigator && "canShare" in _navigator; const share = async (overrideOptions = {}) => { if (isSupported) { const data = __spreadValues$3(__spreadValues$3({}, vueDemi.unref(shareOptions)), vueDemi.unref(overrideOptions)); let granted = true; if (data.files && _navigator.canShare) granted = _navigator.canShare({ files: data.files }); if (granted) return _navigator.share(data); } }; return { isSupported, share }; } function useSpeechRecognition(options = {}) { const { interimResults = true, continuous = true, window = defaultWindow } = options; const lang = vueDemi.ref(options.lang || "en-US"); const isListening = vueDemi.ref(false); const isFinal = vueDemi.ref(false); const result = vueDemi.ref(""); const error = vueDemi.shallowRef(void 0); const toggle = (value = !isListening.value) => { isListening.value = value; }; const start = () => { isListening.value = true; }; const stop = () => { isListening.value = false; }; const SpeechRecognition = window && (window.SpeechRecognition || window.webkitSpeechRecognition); const isSupported = Boolean(SpeechRecognition); let recognition; if (isSupported) { recognition = new SpeechRecognition(); recognition.continuous = continuous; recognition.interimResults = interimResults; recognition.lang = vueDemi.unref(lang); recognition.onstart = () => { isFinal.value = false; }; vueDemi.watch(lang, (lang2) => { if (recognition && !isListening.value) recognition.lang = lang2; }); recognition.onresult = (event) => { const transcript = Array.from(event.results).map((result2) => { isFinal.value = result2.isFinal; return result2[0]; }).map((result2) => result2.transcript).join(""); result.value = transcript; error.value = void 0; }; recognition.onerror = (event) => { error.value = event; }; recognition.onend = () => { isListening.value = false; recognition.lang = vueDemi.unref(lang); }; vueDemi.watch(isListening, () => { if (isListening.value) recognition.start(); else recognition.stop(); }); } shared.tryOnScopeDispose(() => { isListening.value = false; }); return { isSupported, isListening, isFinal, recognition, result, error, toggle, start, stop }; } function useSpeechSynthesis(text, options = {}) { var _a, _b; const { pitch = 1, rate = 1, volume = 1, window = defaultWindow } = options; const synth = window && window.speechSynthesis; const isSupported = Boolean(synth); const isPlaying = vueDemi.ref(false); const status = vueDemi.ref("init"); const voiceInfo = { lang: ((_a = options.voice) == null ? void 0 : _a.lang) || "default", name: ((_b = options.voice) == null ? void 0 : _b.name) || "" }; const spokenText = vueDemi.ref(text || ""); const lang = vueDemi.ref(options.lang || "en-US"); const error = vueDemi.shallowRef(void 0); const toggle = (value = !isPlaying.value) => { isPlaying.value = value; }; const bindEventsForUtterance = (utterance2) => { utterance2.lang = vueDemi.unref(lang); options.voice && (utterance2.voice = options.voice); utterance2.pitch = pitch; utterance2.rate = rate; utterance2.volume = volume; utterance2.onstart = () => { isPlaying.value = true; status.value = "play"; }; utterance2.onpause = () => { isPlaying.value = false; status.value = "pause"; }; utterance2.onresume = () => { isPlaying.value = true; status.value = "play"; }; utterance2.onend = () => { isPlaying.value = false; status.value = "end"; }; utterance2.onerror = (event) => { error.value = event; }; utterance2.onend = () => { isPlaying.value = false; utterance2.lang = vueDemi.unref(lang); }; }; const utterance = vueDemi.computed(() => { isPlaying.value = false; status.value = "init"; const newUtterance = new SpeechSynthesisUtterance(spokenText.value); bindEventsForUtterance(newUtterance); return newUtterance; }); const speak = () => { synth.cancel(); utterance && synth.speak(utterance.value); }; if (isSupported) { bindEventsForUtterance(utterance.value); vueDemi.watch(lang, (lang2) => { if (utterance.value && !isPlaying.value) utterance.value.lang = lang2; }); vueDemi.watch(isPlaying, () => { if (isPlaying.value) synth.resume(); else synth.pause(); }); } shared.tryOnScopeDispose(() => { isPlaying.value = false; }); return { isSupported, isPlaying, status, voiceInfo, utterance, error, toggle, speak }; } function useStorageAsync(key, initialValue, storage, options = {}) { var _a; const { flush = "pre", deep = true, listenToStorageChanges = true, writeDefaults = true, shallow, window = defaultWindow, eventFilter, onError = (e) => { console.error(e); } } = options; const rawInit = vueDemi.unref(initialValue); const type = guessSerializerType(rawInit); const data = (shallow ? vueDemi.shallowRef : vueDemi.ref)(initialValue); const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type]; if (!storage) { try { storage = getSSRHandler("getDefaultStorage", () => { var _a2; return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage; })(); } catch (e) { onError(e); } } async function read(event) { if (!storage || event && event.key !== key) return; try { const rawValue = event ? event.newValue : await storage.getItem(key); if (rawValue == null) { data.value = rawInit; if (writeDefaults && rawInit !== null) await storage.setItem(key, await serializer.write(rawInit)); } else { data.value = await serializer.read(rawValue); } } catch (e) { onError(e); } } read(); if (window && listenToStorageChanges) useEventListener(window, "storage", (e) => setTimeout(() => read(e), 0)); if (storage) { shared.watchWithFilter(data, async () => { try { if (data.value == null) await storage.removeItem(key); else await storage.setItem(key, await serializer.write(data.value)); } catch (e) { onError(e); } }, { flush, deep, eventFilter }); } return data; } let _id = 0; function useStyleTag(css, options = {}) { const isLoaded = vueDemi.ref(false); const { document = defaultDocument, immediate = true, manual = false, id = `vueuse_styletag_${++_id}` } = options; const cssRef = vueDemi.ref(css); let stop = () => { }; const load = () => { if (!document) return; const el = document.getElementById(id) || document.createElement("style"); el.type = "text/css"; el.id = id; if (options.media) el.media = options.media; document.head.appendChild(el); if (isLoaded.value) return; stop = vueDemi.watch(cssRef, (value) => { el.innerText = value; }, { immediate: true }); isLoaded.value = true; }; const unload = () => { if (!document || !isLoaded.value) return; stop(); document.head.removeChild(document.getElementById(id)); isLoaded.value = false; }; if (immediate && !manual) load(); if (!manual) shared.tryOnScopeDispose(unload); return { id, css: cssRef, unload, load, isLoaded: vueDemi.readonly(isLoaded) }; } function useTemplateRefsList() { const refs = vueDemi.ref([]); refs.value.set = (el) => { if (el) refs.value.push(el); }; vueDemi.onBeforeUpdate(() => { refs.value.length = 0; }); return refs; } function getRangesFromSelection(selection) { var _a; const rangeCount = (_a = selection.rangeCount) != null ? _a : 0; const ranges = new Array(rangeCount); for (let i = 0; i < rangeCount; i++) { const range = selection.getRangeAt(i); ranges[i] = range; } return ranges; } function useTextSelection(options = {}) { const { window = defaultWindow } = options; const selection = vueDemi.ref(null); const text = vueDemi.computed(() => { var _a, _b; return (_b = (_a = selection.value) == null ? void 0 : _a.toString()) != null ? _b : ""; }); const ranges = vueDemi.computed(() => selection.value ? getRangesFromSelection(selection.value) : []); const rects = vueDemi.computed(() => ranges.value.map((range) => range.getBoundingClientRect())); function onSelectionChange() { selection.value = null; if (window) selection.value = window.getSelection(); } if (window) useEventListener(window.document, "selectionchange", onSelectionChange); return { text, rects, ranges, selection }; } var __defProp$2 = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; var __hasOwnProp$2 = Object.prototype.hasOwnProperty; var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$2 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$2.call(b, prop)) __defNormalProp$2(a, prop, b[prop]); if (__getOwnPropSymbols$2) for (var prop of __getOwnPropSymbols$2(b)) { if (__propIsEnum$2.call(b, prop)) __defNormalProp$2(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); function useThrottledRefHistory(source, options = {}) { const { throttle = 200, trailing = true } = options; const filter = shared.throttleFilter(throttle, trailing); const history = useRefHistory(source, __spreadProps(__spreadValues$2({}, options), { eventFilter: filter })); return __spreadValues$2({}, history); } var __defProp$1 = Object.defineProperty; var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; var __hasOwnProp$1 = Object.prototype.hasOwnProperty; var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$1 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$1.call(b, prop)) __defNormalProp$1(a, prop, b[prop]); if (__getOwnPropSymbols$1) for (var prop of __getOwnPropSymbols$1(b)) { if (__propIsEnum$1.call(b, prop)) __defNormalProp$1(a, prop, b[prop]); } return a; }; var __objRest = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols$1) for (var prop of __getOwnPropSymbols$1(source)) { if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop)) target[prop] = source[prop]; } return target; }; const UNITS = [ { max: 6e4, value: 1e3, name: "second" }, { max: 276e4, value: 6e4, name: "minute" }, { max: 72e6, value: 36e5, name: "hour" }, { max: 5184e5, value: 864e5, name: "day" }, { max: 24192e5, value: 6048e5, name: "week" }, { max: 28512e6, value: 2592e6, name: "month" }, { max: Infinity, value: 31536e6, name: "year" } ]; const DEFAULT_MESSAGES = { justNow: "just now", past: (n) => n.match(/\d/) ? `${n} ago` : n, future: (n) => n.match(/\d/) ? `in ${n}` : n, month: (n, past) => n === 1 ? past ? "last month" : "next month" : `${n} month${n > 1 ? "s" : ""}`, year: (n, past) => n === 1 ? past ? "last year" : "next year" : `${n} year${n > 1 ? "s" : ""}`, day: (n, past) => n === 1 ? past ? "yesterday" : "tomorrow" : `${n} day${n > 1 ? "s" : ""}`, week: (n, past) => n === 1 ? past ? "last week" : "next week" : `${n} week${n > 1 ? "s" : ""}`, hour: (n) => `${n} hour${n > 1 ? "s" : ""}`, minute: (n) => `${n} minute${n > 1 ? "s" : ""}`, second: (n) => `${n} second${n > 1 ? "s" : ""}` }; const DEFAULT_FORMATTER = (date) => date.toISOString().slice(0, 10); function useTimeAgo(time, options = {}) { const { controls: exposeControls = false, max, updateInterval = 3e4, messages = DEFAULT_MESSAGES, fullDateFormatter = DEFAULT_FORMATTER } = options; const { abs, round } = Math; const _a = useNow({ interval: updateInterval, controls: true }), { now } = _a, controls = __objRest(_a, ["now"]); function getTimeago(from, now2) { var _a2; const diff = +now2 - +from; const absDiff = abs(diff); if (absDiff < 6e4) return messages.justNow; if (typeof max === "number" && absDiff > max) return fullDateFormatter(new Date(from)); if (typeof max === "string") { const unitMax = (_a2 = UNITS.find((i) => i.name === max)) == null ? void 0 : _a2.max; if (unitMax && absDiff > unitMax) return fullDateFormatter(new Date(from)); } for (const unit of UNITS) { if (absDiff < unit.max) return format(diff, unit); } } function applyFormat(name, val, isPast) { const formatter = messages[name]; if (typeof formatter === "function") return formatter(val, isPast); return formatter.replace("{0}", val.toString()); } function format(diff, unit) { const val = round(abs(diff) / unit.value); const past = diff > 0; const str = applyFormat(unit.name, val, past); return applyFormat(past ? "past" : "future", str, past); } const timeAgo = vueDemi.computed(() => getTimeago(new Date(vueDemi.unref(time)), vueDemi.unref(now.value))); if (exposeControls) { return __spreadValues$1({ timeAgo }, controls); } else { return timeAgo; } } function useTimeoutPoll(fn, interval, timeoutPollOptions) { const { start } = shared.useTimeoutFn(loop, interval); const isActive = vueDemi.ref(false); async function loop() { if (!isActive.value) return; await fn(); start(); } function resume() { if (!isActive.value) { isActive.value = true; loop(); } } function pause() { isActive.value = false; } if (timeoutPollOptions == null ? void 0 : timeoutPollOptions.immediate) resume(); shared.tryOnScopeDispose(pause); return { isActive, pause, resume }; } var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; function useTimestamp(options = {}) { const { controls: exposeControls = false, offset = 0, immediate = true, interval = "requestAnimationFrame" } = options; const ts = vueDemi.ref(shared.timestamp() + offset); const update = () => ts.value = shared.timestamp() + offset; const controls = interval === "requestAnimationFrame" ? useRafFn(update, { immediate }) : shared.useIntervalFn(update, interval, { immediate }); if (exposeControls) { return __spreadValues({ timestamp: ts }, controls); } else { return ts; } } function useTitle(newTitle = null, options = {}) { var _a, _b; const { document = defaultDocument, observe = false, titleTemplate = "%s" } = options; const title = vueDemi.ref((_a = newTitle != null ? newTitle : document == null ? void 0 : document.title) != null ? _a : null); vueDemi.watch(title, (t, o) => { if (shared.isString(t) && t !== o && document) document.title = titleTemplate.replace("%s", t); }, { immediate: true }); if (observe && document) { useMutationObserver((_b = document.head) == null ? void 0 : _b.querySelector("title"), () => { if (document && document.title !== title.value) title.value = titleTemplate.replace("%s", document.title); }, { childList: true }); } return title; } const TransitionPresets = { linear: shared.identity, easeInSine: [0.12, 0, 0.39, 0], easeOutSine: [0.61, 1, 0.88, 1], easeInOutSine: [0.37, 0, 0.63, 1], easeInQuad: [0.11, 0, 0.5, 0], easeOutQuad: [0.5, 1, 0.89, 1], easeInOutQuad: [0.45, 0, 0.55, 1], easeInCubic: [0.32, 0, 0.67, 0], easeOutCubic: [0.33, 1, 0.68, 1], easeInOutCubic: [0.65, 0, 0.35, 1], easeInQuart: [0.5, 0, 0.75, 0], easeOutQuart: [0.25, 1, 0.5, 1], easeInOutQuart: [0.76, 0, 0.24, 1], easeInQuint: [0.64, 0, 0.78, 0], easeOutQuint: [0.22, 1, 0.36, 1], easeInOutQuint: [0.83, 0, 0.17, 1], easeInExpo: [0.7, 0, 0.84, 0], easeOutExpo: [0.16, 1, 0.3, 1], easeInOutExpo: [0.87, 0, 0.13, 1], easeInCirc: [0.55, 0, 1, 0.45], easeOutCirc: [0, 0.55, 0.45, 1], easeInOutCirc: [0.85, 0, 0.15, 1], easeInBack: [0.36, 0, 0.66, -0.56], easeOutBack: [0.34, 1.56, 0.64, 1], easeInOutBack: [0.68, -0.6, 0.32, 1.6] }; function createEasingFunction([p0, p1, p2, p3]) { const a = (a1, a2) => 1 - 3 * a2 + 3 * a1; const b = (a1, a2) => 3 * a2 - 6 * a1; const c = (a1) => 3 * a1; const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; const getSlope = (t, a1, a2) => 3 * a(a1, a2) * t * t + 2 * b(a1, a2) * t + c(a1); const getTforX = (x) => { let aGuessT = x; for (let i = 0; i < 4; ++i) { const currentSlope = getSlope(aGuessT, p0, p2); if (currentSlope === 0) return aGuessT; const currentX = calcBezier(aGuessT, p0, p2) - x; aGuessT -= currentX / currentSlope; } return aGuessT; }; return (x) => p0 === p1 && p2 === p3 ? x : calcBezier(getTforX(x), p1, p3); } function useTransition(source, options = {}) { const { delay = 0, disabled = false, duration = 1e3, onFinished = shared.noop, onStarted = shared.noop, transition = shared.identity } = options; const currentTransition = vueDemi.computed(() => { const t = vueDemi.unref(transition); return shared.isFunction(t) ? t : createEasingFunction(t); }); const sourceValue = vueDemi.computed(() => { const s = vueDemi.unref(source); return shared.isNumber(s) ? s : s.map(vueDemi.unref); }); const sourceVector = vueDemi.computed(() => shared.isNumber(sourceValue.value) ? [sourceValue.value] : sourceValue.value); const outputVector = vueDemi.ref(sourceVector.value.slice(0)); let currentDuration; let diffVector; let endAt; let startAt; let startVector; const { resume, pause } = useRafFn(() => { const now = Date.now(); const progress = shared.clamp(1 - (endAt - now) / currentDuration, 0, 1); outputVector.value = startVector.map((val, i) => { var _a; return val + ((_a = diffVector[i]) != null ? _a : 0) * currentTransition.value(progress); }); if (progress >= 1) { pause(); onFinished(); } }, { immediate: false }); const start = () => { pause(); currentDuration = vueDemi.unref(duration); diffVector = outputVector.value.map((n, i) => { var _a, _b; return ((_a = sourceVector.value[i]) != null ? _a : 0) - ((_b = outputVector.value[i]) != null ? _b : 0); }); startVector = outputVector.value.slice(0); startAt = Date.now(); endAt = startAt + currentDuration; resume(); onStarted(); }; const timeout = shared.useTimeoutFn(start, delay, { immediate: false }); vueDemi.watch(sourceVector, () => { if (vueDemi.unref(disabled)) { outputVector.value = sourceVector.value.slice(0); } else { if (vueDemi.unref(delay) <= 0) start(); else timeout.start(); } }, { deep: true }); return vueDemi.computed(() => { const targetVector = vueDemi.unref(disabled) ? sourceVector : outputVector; return shared.isNumber(sourceValue.value) ? targetVector.value[0] : targetVector.value; }); } function useUrlSearchParams(mode = "history", options = {}) { const { initialValue = {}, removeNullishValues = true, removeFalsyValues = false, window = defaultWindow } = options; if (!window) return vueDemi.reactive(initialValue); const state = vueDemi.reactive(initialValue); function getRawParams() { if (mode === "history") { return window.location.search || ""; } else if (mode === "hash") { const hash = window.location.hash || ""; const index = hash.indexOf("?"); return index > 0 ? hash.slice(index) : ""; } else { return (window.location.hash || "").replace(/^#/, ""); } } function constructQuery(params) { const stringified = params.toString(); if (mode === "history") return `${stringified ? `?${stringified}` : ""}${location.hash || ""}`; if (mode === "hash-params") return `${location.search || ""}${stringified ? `#${stringified}` : ""}`; const hash = window.location.hash || "#"; const index = hash.indexOf("?"); if (index > 0) return `${hash.slice(0, index)}${stringified ? `?${stringified}` : ""}`; return `${hash}${stringified ? `?${stringified}` : ""}`; } function read() { return new URLSearchParams(getRawParams()); } function updateState(params) { const unusedKeys = new Set(Object.keys(state)); for (const key of params.keys()) { const paramsForKey = params.getAll(key); state[key] = paramsForKey.length > 1 ? paramsForKey : params.get(key) || ""; unusedKeys.delete(key); } Array.from(unusedKeys).forEach((key) => delete state[key]); } const { pause, resume } = shared.pausableWatch(state, () => { const params = new URLSearchParams(""); Object.keys(state).forEach((key) => { const mapEntry = state[key]; if (Array.isArray(mapEntry)) mapEntry.forEach((value) => params.append(key, value)); else if (removeNullishValues && mapEntry == null) params.delete(key); else if (removeFalsyValues && !mapEntry) params.delete(key); else params.set(key, mapEntry); }); write(params); }, { deep: true }); function write(params, shouldUpdate) { pause(); if (shouldUpdate) updateState(params); window.history.replaceState({}, "", window.location.pathname + constructQuery(params)); resume(); } function onChanged() { write(read(), true); } useEventListener(window, "popstate", onChanged, false); if (mode !== "history") useEventListener(window, "hashchange", onChanged, false); updateState(read()); return state; } function useUserMedia(options = {}) { var _a, _b, _c; const enabled = vueDemi.ref((_a = options.enabled) != null ? _a : false); const autoSwitch = vueDemi.ref((_b = options.autoSwitch) != null ? _b : true); const videoDeviceId = vueDemi.ref(options.videoDeviceId); const audioDeviceId = vueDemi.ref(options.audioDeviceId); const { navigator = defaultNavigator } = options; const isSupported = Boolean((_c = navigator == null ? void 0 : navigator.mediaDevices) == null ? void 0 : _c.getUserMedia); const stream = vueDemi.shallowRef(); function getDeviceOptions(device) { if (device.value === "none" || device.value === false) return false; if (device.value == null) return true; return { deviceId: device.value }; } async function _start() { if (!isSupported || stream.value) return; stream.value = await navigator.mediaDevices.getUserMedia({ video: getDeviceOptions(videoDeviceId), audio: getDeviceOptions(audioDeviceId) }); return stream.value; } async function _stop() { var _a2; (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop()); stream.value = void 0; } function stop() { _stop(); enabled.value = false; } async function start() { await _start(); if (stream.value) enabled.value = true; return stream.value; } async function restart() { _stop(); return await start(); } vueDemi.watch(enabled, (v) => { if (v) _start(); else _stop(); }, { immediate: true }); vueDemi.watch([videoDeviceId, audioDeviceId], () => { if (autoSwitch.value && stream.value) restart(); }, { immediate: true }); return { isSupported, stream, start, stop, restart, videoDeviceId, audioDeviceId, enabled, autoSwitch }; } function useVModel(props, key, emit, options = {}) { var _a, _b, _c; const { passive = false, eventName, deep = false } = options; const vm = vueDemi.getCurrentInstance(); const _emit = emit || (vm == null ? void 0 : vm.emit) || ((_a = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a.bind(vm)); let event = eventName; if (!key) { if (vueDemi.isVue2) { const modelOptions = (_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$options) == null ? void 0 : _c.model; key = (modelOptions == null ? void 0 : modelOptions.value) || "value"; if (!eventName) event = (modelOptions == null ? void 0 : modelOptions.event) || "input"; } else { key = "modelValue"; } } event = eventName || event || `update:${key}`; if (passive) { const proxy = vueDemi.ref(props[key]); vueDemi.watch(() => props[key], (v) => proxy.value = v); vueDemi.watch(proxy, (v) => { if (v !== props[key] || deep) _emit(event, v); }, { deep }); return proxy; } else { return vueDemi.computed({ get() { return props[key]; }, set(value) { _emit(event, value); } }); } } function useVModels(props, emit, options = {}) { const ret = {}; for (const key in props) ret[key] = useVModel(props, key, emit, options); return ret; } function useVibrate(options) { const { pattern = [], interval = 0, navigator = defaultNavigator } = options || {}; const isSupported = typeof navigator !== "undefined" && "vibrate" in navigator; const patternRef = vueDemi.ref(pattern); let intervalControls; const vibrate = (pattern2 = patternRef.value) => { if (isSupported) navigator.vibrate(pattern2); }; const stop = () => { if (isSupported) navigator.vibrate(0); intervalControls == null ? void 0 : intervalControls.pause(); }; if (interval > 0) { intervalControls = shared.useIntervalFn(vibrate, interval, { immediate: false, immediateCallback: false }); } return { isSupported, pattern, intervalControls, vibrate, stop }; } function useVirtualList(list, options) { const containerRef = vueDemi.ref(); const size = useElementSize(containerRef); const currentList = vueDemi.ref([]); const source = vueDemi.shallowRef(list); const state = vueDemi.ref({ start: 0, end: 10 }); const { itemHeight, overscan = 5 } = options; const getViewCapacity = (containerHeight) => { if (typeof itemHeight === "number") return Math.ceil(containerHeight / itemHeight); const { start = 0 } = state.value; let sum = 0; let capacity = 0; for (let i = start; i < source.value.length; i++) { const height = itemHeight(i); sum += height; if (sum >= containerHeight) { capacity = i; break; } } return capacity - start; }; const getOffset = (scrollTop) => { if (typeof itemHeight === "number") return Math.floor(scrollTop / itemHeight) + 1; let sum = 0; let offset = 0; for (let i = 0; i < source.value.length; i++) { const height = itemHeight(i); sum += height; if (sum >= scrollTop) { offset = i; break; } } return offset + 1; }; const calculateRange = () => { const element = containerRef.value; if (element) { const offset = getOffset(element.scrollTop); const viewCapacity = getViewCapacity(element.clientHeight); const from = offset - overscan; const to = offset + viewCapacity + overscan; state.value = { start: from < 0 ? 0 : from, end: to > source.value.length ? source.value.length : to }; currentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index) => ({ data: ele, index: index + state.value.start })); } }; vueDemi.watch([size.width, size.height, list], () => { calculateRange(); }); const totalHeight = vueDemi.computed(() => { if (typeof itemHeight === "number") return source.value.length * itemHeight; return source.value.reduce((sum, _, index) => sum + itemHeight(index), 0); }); const getDistanceTop = (index) => { if (typeof itemHeight === "number") { const height2 = index * itemHeight; return height2; } const height = source.value.slice(0, index).reduce((sum, _, i) => sum + itemHeight(i), 0); return height; }; const scrollTo = (index) => { if (containerRef.value) { containerRef.value.scrollTop = getDistanceTop(index); calculateRange(); } }; const offsetTop = vueDemi.computed(() => getDistanceTop(state.value.start)); const wrapperProps = vueDemi.computed(() => { return { style: { width: "100%", height: `${totalHeight.value - offsetTop.value}px`, marginTop: `${offsetTop.value}px` } }; }); const containerStyle = { overflowY: "auto" }; return { list: currentList, scrollTo, containerProps: { ref: containerRef, onScroll: () => { calculateRange(); }, style: containerStyle }, wrapperProps }; } const useWakeLock = (options = {}) => { const { navigator = defaultNavigator, document = defaultDocument } = options; let wakeLock; const isSupported = navigator && "wakeLock" in navigator; const isActive = vueDemi.ref(false); async function onVisibilityChange() { if (!isSupported || !wakeLock) return; if (document && document.visibilityState === "visible") wakeLock = await navigator.wakeLock.request("screen"); isActive.value = !wakeLock.released; } if (document) useEventListener(document, "visibilitychange", onVisibilityChange, { passive: true }); async function request(type) { if (!isSupported) return; wakeLock = await navigator.wakeLock.request(type); isActive.value = !wakeLock.released; } async function release() { if (!isSupported || !wakeLock) return; await wakeLock.release(); isActive.value = !wakeLock.released; wakeLock = null; } return { isSupported, isActive, request, release }; }; const useWebNotification = (defaultOptions = {}) => { const { window = defaultWindow } = defaultOptions; const isSupported = !!window && "Notification" in window; const notification = vueDemi.ref(null); const requestPermission = async () => { if (!isSupported) return; if ("permission" in Notification && Notification.permission !== "denied") await Notification.requestPermission(); }; const onClick = shared.createEventHook(); const onShow = shared.createEventHook(); const onError = shared.createEventHook(); const onClose = shared.createEventHook(); const show = async (overrides) => { if (!isSupported) return; await requestPermission(); const options = Object.assign({}, defaultOptions, overrides); notification.value = new Notification(options.title || "", options); notification.value.onclick = (event) => onClick.trigger(event); notification.value.onshow = (event) => onShow.trigger(event); notification.value.onerror = (event) => onError.trigger(event); notification.value.onclose = (event) => onClose.trigger(event); return notification.value; }; const close = () => { if (notification.value) notification.value.close(); notification.value = null; }; shared.tryOnMounted(async () => { if (isSupported) await requestPermission(); }); shared.tryOnScopeDispose(close); if (isSupported && window) { const document = window.document; useEventListener(document, "visibilitychange", (e) => { e.preventDefault(); if (document.visibilityState === "visible") { close(); } }); } return { isSupported, notification, show, close, onClick, onShow, onError, onClose }; }; function resolveNestedOptions(options) { if (options === true) return {}; return options; } function useWebSocket(url, options = {}) { const { onConnected, onDisconnected, onError, onMessage, immediate = true, autoClose = true, protocols = [] } = options; const data = vueDemi.ref(null); const status = vueDemi.ref("CONNECTING"); const wsRef = vueDemi.ref(); let heartbeatPause; let heartbeatResume; let explicitlyClosed = false; let retried = 0; let bufferedData = []; const close = (code = 1e3, reason) => { if (!wsRef.value) return; explicitlyClosed = true; heartbeatPause == null ? void 0 : heartbeatPause(); wsRef.value.close(code, reason); }; const _sendBuffer = () => { if (bufferedData.length && wsRef.value && status.value === "OPEN") { for (const buffer of bufferedData) wsRef.value.send(buffer); bufferedData = []; } }; const send = (data2, useBuffer = true) => { if (!wsRef.value || status.value !== "OPEN") { if (useBuffer) bufferedData.push(data2); return false; } _sendBuffer(); wsRef.value.send(data2); return true; }; const _init = () => { const ws = new WebSocket(url, protocols); wsRef.value = ws; status.value = "CONNECTING"; explicitlyClosed = false; ws.onopen = () => { status.value = "OPEN"; onConnected == null ? void 0 : onConnected(ws); heartbeatResume == null ? void 0 : heartbeatResume(); _sendBuffer(); }; ws.onclose = (ev) => { status.value = "CLOSED"; wsRef.value = void 0; onDisconnected == null ? void 0 : onDisconnected(ws, ev); if (!explicitlyClosed && options.autoReconnect) { const { retries = -1, delay = 1e3, onFailed } = resolveNestedOptions(options.autoReconnect); retried += 1; if (typeof retries === "number" && (retries < 0 || retried < retries)) setTimeout(_init, delay); else if (typeof retries === "function" && retries()) setTimeout(_init, delay); else onFailed == null ? void 0 : onFailed(); } }; ws.onerror = (e) => { onError == null ? void 0 : onError(ws, e); }; ws.onmessage = (e) => { data.value = e.data; onMessage == null ? void 0 : onMessage(ws, e); }; }; if (options.heartbeat) { const { message = "ping", interval = 1e3 } = resolveNestedOptions(options.heartbeat); const { pause, resume } = shared.useIntervalFn(() => send(message, false), interval, { immediate: false }); heartbeatPause = pause; heartbeatResume = resume; } if (immediate) _init(); if (autoClose) { useEventListener(window, "beforeunload", () => close()); shared.tryOnScopeDispose(close); } const open = () => { close(); retried = 0; _init(); }; return { data, status, close, send, open, ws: wsRef }; } function useWebWorker(url, workerOptions, options = {}) { const { window = defaultWindow } = options; const data = vueDemi.ref(null); const worker = vueDemi.shallowRef(); const post = function post2(val) { if (!worker.value) return; worker.value.postMessage(val); }; const terminate = function terminate2() { if (!worker.value) return; worker.value.terminate(); }; if (window) { worker.value = new Worker(url, workerOptions); worker.value.onmessage = (e) => { data.value = e.data; }; shared.tryOnScopeDispose(() => { if (worker.value) worker.value.terminate(); }); } return { data, post, terminate, worker }; } const jobRunner = (userFunc) => (e) => { const userFuncArgs = e.data[0]; return Promise.resolve(userFunc.apply(void 0, userFuncArgs)).then((result) => { postMessage(["SUCCESS", result]); }).catch((error) => { postMessage(["ERROR", error]); }); }; const depsParser = (deps) => { if (deps.length === 0) return ""; const depsString = deps.map((dep) => `'${dep}'`).toString(); return `importScripts(${depsString})`; }; const createWorkerBlobUrl = (fn, deps) => { const blobCode = `${depsParser(deps)}; onmessage=(${jobRunner})(${fn})`; const blob = new Blob([blobCode], { type: "text/javascript" }); const url = URL.createObjectURL(blob); return url; }; const useWebWorkerFn = (fn, options = {}) => { const { dependencies = [], timeout, window = defaultWindow } = options; const worker = vueDemi.ref(); const workerStatus = vueDemi.ref("PENDING"); const promise = vueDemi.ref({}); const timeoutId = vueDemi.ref(); const workerTerminate = (status = "PENDING") => { if (worker.value && worker.value._url && window) { worker.value.terminate(); URL.revokeObjectURL(worker.value._url); promise.value = {}; worker.value = void 0; window.clearTimeout(timeoutId.value); workerStatus.value = status; } }; workerTerminate(); shared.tryOnScopeDispose(workerTerminate); const generateWorker = () => { const blobUrl = createWorkerBlobUrl(fn, dependencies); const newWorker = new Worker(blobUrl); newWorker._url = blobUrl; newWorker.onmessage = (e) => { const { resolve = () => { }, reject = () => { } } = promise.value; const [status, result] = e.data; switch (status) { case "SUCCESS": resolve(result); workerTerminate(status); break; default: reject(result); workerTerminate("ERROR"); break; } }; newWorker.onerror = (e) => { const { reject = () => { } } = promise.value; reject(e); workerTerminate("ERROR"); }; if (timeout) { timeoutId.value = setTimeout(() => workerTerminate("TIMEOUT_EXPIRED"), timeout); } return newWorker; }; const callWorker = (...fnArgs) => new Promise((resolve, reject) => { promise.value = { resolve, reject }; worker.value && worker.value.postMessage([[...fnArgs]]); workerStatus.value = "RUNNING"; }); const workerFn = (...fnArgs) => { if (workerStatus.value === "RUNNING") { console.error("[useWebWorkerFn] You can only run one instance of the worker at a time."); return Promise.reject(); } worker.value = generateWorker(); return callWorker(...fnArgs); }; return { workerFn, workerStatus, workerTerminate }; }; function useWindowFocus({ window = defaultWindow } = {}) { if (!window) return vueDemi.ref(false); const focused = vueDemi.ref(window.document.hasFocus()); useEventListener(window, "blur", () => { focused.value = false; }); useEventListener(window, "focus", () => { focused.value = true; }); return focused; } function useWindowScroll({ window = defaultWindow } = {}) { if (!window) { return { x: vueDemi.ref(0), y: vueDemi.ref(0) }; } const x = vueDemi.ref(window.pageXOffset); const y = vueDemi.ref(window.pageYOffset); useEventListener("scroll", () => { x.value = window.pageXOffset; y.value = window.pageYOffset; }, { capture: false, passive: true }); return { x, y }; } function useWindowSize({ window = defaultWindow, initialWidth = Infinity, initialHeight = Infinity } = {}) { const width = vueDemi.ref(initialWidth); const height = vueDemi.ref(initialHeight); const update = () => { if (window) { width.value = window.innerWidth; height.value = window.innerHeight; } }; update(); shared.tryOnMounted(update); useEventListener("resize", update, { passive: true }); return { width, height }; } exports.DefaultMagicKeysAliasMap = DefaultMagicKeysAliasMap; exports.StorageSerializers = StorageSerializers; exports.SwipeDirection = SwipeDirection; exports.TransitionPresets = TransitionPresets; exports.asyncComputed = computedAsync; exports.breakpointsAntDesign = breakpointsAntDesign; exports.breakpointsBootstrapV5 = breakpointsBootstrapV5; exports.breakpointsQuasar = breakpointsQuasar; exports.breakpointsSematic = breakpointsSematic; exports.breakpointsTailwind = breakpointsTailwind; exports.breakpointsVuetify = breakpointsVuetify; exports.computedAsync = computedAsync; exports.computedInject = computedInject; exports.createFetch = createFetch; exports.createUnrefFn = createUnrefFn; exports.defaultDocument = defaultDocument; exports.defaultLocation = defaultLocation; exports.defaultNavigator = defaultNavigator; exports.defaultWindow = defaultWindow; exports.getSSRHandler = getSSRHandler; exports.mapGamepadToXbox360Controller = mapGamepadToXbox360Controller; exports.onClickOutside = onClickOutside; exports.onKeyDown = onKeyDown; exports.onKeyPressed = onKeyPressed; exports.onKeyStroke = onKeyStroke; exports.onKeyUp = onKeyUp; exports.onLongPress = onLongPress; exports.onStartTyping = onStartTyping; exports.setSSRHandler = setSSRHandler; exports.templateRef = templateRef; exports.unrefElement = unrefElement; exports.useActiveElement = useActiveElement; exports.useAsyncQueue = useAsyncQueue; exports.useAsyncState = useAsyncState; exports.useBase64 = useBase64; exports.useBattery = useBattery; exports.useBreakpoints = useBreakpoints; exports.useBroadcastChannel = useBroadcastChannel; exports.useBrowserLocation = useBrowserLocation; exports.useCached = useCached; exports.useClamp = useClamp; exports.useClipboard = useClipboard; exports.useColorMode = useColorMode; exports.useConfirmDialog = useConfirmDialog; exports.useCssVar = useCssVar; exports.useCycleList = useCycleList; exports.useDark = useDark; exports.useDebouncedRefHistory = useDebouncedRefHistory; exports.useDeviceMotion = useDeviceMotion; exports.useDeviceOrientation = useDeviceOrientation; exports.useDevicePixelRatio = useDevicePixelRatio; exports.useDevicesList = useDevicesList; exports.useDisplayMedia = useDisplayMedia; exports.useDocumentVisibility = useDocumentVisibility; exports.useDraggable = useDraggable; exports.useElementBounding = useElementBounding; exports.useElementByPoint = useElementByPoint; exports.useElementHover = useElementHover; exports.useElementSize = useElementSize; exports.useElementVisibility = useElementVisibility; exports.useEventBus = useEventBus; exports.useEventListener = useEventListener; exports.useEventSource = useEventSource; exports.useEyeDropper = useEyeDropper; exports.useFavicon = useFavicon; exports.useFetch = useFetch; exports.useFileSystemAccess = useFileSystemAccess; exports.useFocus = useFocus; exports.useFocusWithin = useFocusWithin; exports.useFps = useFps; exports.useFullscreen = useFullscreen; exports.useGamepad = useGamepad; exports.useGeolocation = useGeolocation; exports.useIdle = useIdle; exports.useInfiniteScroll = useInfiniteScroll; exports.useIntersectionObserver = useIntersectionObserver; exports.useKeyModifier = useKeyModifier; exports.useLocalStorage = useLocalStorage; exports.useMagicKeys = useMagicKeys; exports.useManualRefHistory = useManualRefHistory; exports.useMediaControls = useMediaControls; exports.useMediaQuery = useMediaQuery; exports.useMemoize = useMemoize; exports.useMemory = useMemory; exports.useMounted = useMounted; exports.useMouse = useMouse; exports.useMouseInElement = useMouseInElement; exports.useMousePressed = useMousePressed; exports.useMutationObserver = useMutationObserver; exports.useNavigatorLanguage = useNavigatorLanguage; exports.useNetwork = useNetwork; exports.useNow = useNow; exports.useOffsetPagination = useOffsetPagination; exports.useOnline = useOnline; exports.usePageLeave = usePageLeave; exports.useParallax = useParallax; exports.usePermission = usePermission; exports.usePointer = usePointer; exports.usePointerSwipe = usePointerSwipe; exports.usePreferredColorScheme = usePreferredColorScheme; exports.usePreferredDark = usePreferredDark; exports.usePreferredLanguages = usePreferredLanguages; exports.useRafFn = useRafFn; exports.useRefHistory = useRefHistory; exports.useResizeObserver = useResizeObserver; exports.useScreenSafeArea = useScreenSafeArea; exports.useScriptTag = useScriptTag; exports.useScroll = useScroll; exports.useScrollLock = useScrollLock; exports.useSessionStorage = useSessionStorage; exports.useShare = useShare; exports.useSpeechRecognition = useSpeechRecognition; exports.useSpeechSynthesis = useSpeechSynthesis; exports.useStorage = useStorage; exports.useStorageAsync = useStorageAsync; exports.useStyleTag = useStyleTag; exports.useSwipe = useSwipe; exports.useTemplateRefsList = useTemplateRefsList; exports.useTextSelection = useTextSelection; exports.useThrottledRefHistory = useThrottledRefHistory; exports.useTimeAgo = useTimeAgo; exports.useTimeoutPoll = useTimeoutPoll; exports.useTimestamp = useTimestamp; exports.useTitle = useTitle; exports.useTransition = useTransition; exports.useUrlSearchParams = useUrlSearchParams; exports.useUserMedia = useUserMedia; exports.useVModel = useVModel; exports.useVModels = useVModels; exports.useVibrate = useVibrate; exports.useVirtualList = useVirtualList; exports.useWakeLock = useWakeLock; exports.useWebNotification = useWebNotification; exports.useWebSocket = useWebSocket; exports.useWebWorker = useWebWorker; exports.useWebWorkerFn = useWebWorkerFn; exports.useWindowFocus = useWindowFocus; exports.useWindowScroll = useWindowScroll; exports.useWindowSize = useWindowSize; Object.keys(shared).forEach(function (k) { if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, { enumerable: true, get: function () { return shared[k]; } }); }); Object.defineProperty(exports, '__esModule', { value: true }); })(this.VueUse = this.VueUse || {}, VueUse, VueDemi, VueUse);
const Settings = require('../settings'); class User { constructor(userData) { this.userData = userData; this.invalidDecks = undefined; } get _id() { return this.userData._id; } get disabled() { return this.userData.disabled; } get username() { return this.userData.username; } get tokens() { return this.userData.tokens; } get activationToken() { return this.userData.activationToken; } get activationTokenExpiry() { return this.userData.activationTokenExpiry; } get resetToken() { return this.userData.resetToken; } get tokenExpires() { return this.userData.tokenExpires; } get blockList() { return this.userData.blockList || []; } set blockList(value) { this.userData.blockList = value; } get password() { return this.userData.password; } get permissions() { return this.userData.permissions || []; } get email() { return this.userData.email; } get enableGravatar() { return this.userData.enableGravatar; } get verified() { return this.userData.verified; } get registered() { return this.userData.registered; } get isAdmin() { return this.userData.permissions && this.userData.permissions.isAdmin; } get isContributor() { return this.userData.permissions && this.userData.permissions.isContributor; } get isSupporter() { return this.userData.permissions && this.userData.permissions.isSupporter; } get role() { if(this.isAdmin) { return 'admin'; } if(this.isContributor) { return 'contributor'; } if(this.isSupporter) { return 'supporter'; } return 'user'; } get patreon() { return this.userData.patreon; } set patreon(value) { this.userData.patreon = value; } block(otherUser) { this.userData.blockList = this.userData.blockList || []; this.userData.blockList.push(otherUser.username.toLowerCase()); } hasUserBlocked(otherUser) { return this.blockList.includes(otherUser.username.toLowerCase()); } getWireSafeDetails() { let user = { _id: this.userData._id, username: this.userData.username, email: this.userData.email, settings: this.userData.settings, promptedActionWindows: this.userData.promptedActionWindows, permissions: this.userData.permissions, verified: this.userData.verified, enableGravatar: this.userData.enableGravatar }; user = Settings.getUserWithDefaultsSet(user); return user; } getShortSummary() { return { username: this.username, name: this.username, role: this.role }; } getFullDetails() { let user = Object.assign({ invalidDecks: this.invalidDecks }, this.userData); delete user.password; user = Settings.getUserWithDefaultsSet(user); return user; } getDetails() { let user = Object.assign({ invalidDecks: this.invalidDecks }, this.userData); delete user.password; delete user.tokens; user = Settings.getUserWithDefaultsSet(user); user.role = this.role; return user; } } module.exports = User;
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const async = require("async"); const crypto = require("crypto"); const Tapable = require("tapable"); const EntryModuleNotFoundError = require("./EntryModuleNotFoundError"); const ModuleNotFoundError = require("./ModuleNotFoundError"); const ModuleDependencyWarning = require("./ModuleDependencyWarning"); const ModuleDependencyError = require("./ModuleDependencyError"); const Module = require("./Module"); const Chunk = require("./Chunk"); const Entrypoint = require("./Entrypoint"); const Stats = require("./Stats"); const MainTemplate = require("./MainTemplate"); const ChunkTemplate = require("./ChunkTemplate"); const HotUpdateChunkTemplate = require("./HotUpdateChunkTemplate"); const ModuleTemplate = require("./ModuleTemplate"); const Dependency = require("./Dependency"); const ChunkRenderError = require("./ChunkRenderError"); const CachedSource = require("webpack-sources").CachedSource; function byId(a, b) { if(a.id < b.id) return -1; if(a.id > b.id) return 1; return 0; } function iterationBlockVariable(variables, fn) { for(let indexVariable = 0; indexVariable < variables.length; indexVariable++) { let varDep = variables[indexVariable].dependencies; for(let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { fn(varDep[indexVDep]); } } } function iterationOfArrayCallback(arr, fn) { for(let index = 0; index < arr.length; index++) { fn(arr[index]); } } class Compilation extends Tapable { constructor(compiler) { super(); this.compiler = compiler; this.resolvers = compiler.resolvers; this.inputFileSystem = compiler.inputFileSystem; const options = this.options = compiler.options; this.outputOptions = options && options.output; this.bail = options && options.bail; this.profile = options && options.profile; this.performance = options && options.performance; this.mainTemplate = new MainTemplate(this.outputOptions); this.chunkTemplate = new ChunkTemplate(this.outputOptions); this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate(this.outputOptions); this.moduleTemplate = new ModuleTemplate(this.outputOptions); this.entries = []; this.preparedChunks = []; this.entrypoints = {}; this.chunks = []; this.namedChunks = {}; this.modules = []; this._modules = {}; this.cache = null; this.records = null; this.nextFreeModuleIndex = undefined; this.nextFreeModuleIndex2 = undefined; this.additionalChunkAssets = []; this.assets = {}; this.errors = []; this.warnings = []; this.children = []; this.dependencyFactories = new Map(); this.dependencyTemplates = new Map(); } templatesPlugin(name, fn) { this.mainTemplate.plugin(name, fn); this.chunkTemplate.plugin(name, fn); } addModule(module, cacheGroup) { const identifier = module.identifier(); if(this._modules[identifier]) { return false; } const cacheName = (cacheGroup || "m") + identifier; if(this.cache && this.cache[cacheName]) { const cacheModule = this.cache[cacheName]; let rebuild = true; if(!cacheModule.error && cacheModule.cacheable && this.fileTimestamps && this.contextTimestamps) { rebuild = cacheModule.needRebuild(this.fileTimestamps, this.contextTimestamps); } if(!rebuild) { cacheModule.disconnect(); this._modules[identifier] = cacheModule; this.modules.push(cacheModule); cacheModule.errors.forEach(err => this.errors.push(err), this); cacheModule.warnings.forEach(err => this.warnings.push(err), this); return cacheModule; } else { module.lastId = cacheModule.id; } } module.unbuild(); this._modules[identifier] = module; if(this.cache) { this.cache[cacheName] = module; } this.modules.push(module); return true; } getModule(module) { const identifier = module.identifier(); return this._modules[identifier]; } findModule(identifier) { return this._modules[identifier]; } buildModule(module, optional, origin, dependencies, thisCallback) { this.applyPlugins1("build-module", module); if(module.building) return module.building.push(thisCallback); const building = module.building = [thisCallback]; function callback(err) { module.building = undefined; building.forEach(cb => cb(err)); } module.build(this.options, this, this.resolvers.normal, this.inputFileSystem, (error) => { const errors = module.errors; for(let indexError = 0; indexError < errors.length; indexError++) { const err = errors[indexError]; err.origin = origin; err.dependencies = dependencies; if(optional) this.warnings.push(err); else this.errors.push(err); } const warnings = module.warnings; for(let indexWarning = 0; indexWarning < warnings.length; indexWarning++) { const war = warnings[indexWarning]; war.origin = origin; war.dependencies = dependencies; this.warnings.push(war); } module.dependencies.sort(Dependency.compare); if(error) { this.applyPlugins2("failed-module", module, error); return callback(error); } this.applyPlugins1("succeed-module", module); return callback(); }); } processModuleDependencies(module, callback) { const dependencies = []; function addDependency(dep) { for(let i = 0; i < dependencies.length; i++) { if(dep.isEqualResource(dependencies[i][0])) { return dependencies[i].push(dep); } } dependencies.push([dep]); } function addDependenciesBlock(block) { if(block.dependencies) { iterationOfArrayCallback(block.dependencies, addDependency); } if(block.blocks) { iterationOfArrayCallback(block.blocks, addDependenciesBlock); } if(block.variables) { iterationBlockVariable(block.variables, addDependency); } } addDependenciesBlock(module); this.addModuleDependencies(module, dependencies, this.bail, null, true, callback); } addModuleDependencies(module, dependencies, bail, cacheGroup, recursive, callback) { let _this = this; const start = _this.profile && +new Date(); const factories = []; for(let i = 0; i < dependencies.length; i++) { const factory = _this.dependencyFactories.get(dependencies[i][0].constructor); if(!factory) { return callback(new Error(`No module factory available for dependency type: ${dependencies[i][0].constructor.name}`)); } factories[i] = [factory, dependencies[i]]; } async.forEach(factories, function iteratorFactory(item, callback) { const dependencies = item[1]; const errorAndCallback = function errorAndCallback(err) { err.origin = module; _this.errors.push(err); if(bail) { callback(err); } else { callback(); } }; const warningAndCallback = function warningAndCallback(err) { err.origin = module; _this.warnings.push(err); callback(); }; const factory = item[0]; factory.create({ contextInfo: { issuer: module.nameForCondition && module.nameForCondition(), compiler: _this.compiler.name }, context: module.context, dependencies: dependencies }, function factoryCallback(err, dependentModule) { let afterFactory; function isOptional() { return dependencies.filter(d => !d.optional).length === 0; } function errorOrWarningAndCallback(err) { if(isOptional()) { return warningAndCallback(err); } else { return errorAndCallback(err); } } function iterationDependencies(depend) { for(let index = 0; index < depend.length; index++) { const dep = depend[index]; dep.module = dependentModule; dependentModule.addReason(module, dep); } } if(err) { return errorOrWarningAndCallback(new ModuleNotFoundError(module, err, dependencies)); } if(!dependentModule) { return process.nextTick(callback); } if(_this.profile) { if(!dependentModule.profile) { dependentModule.profile = {}; } afterFactory = +new Date(); dependentModule.profile.factory = afterFactory - start; } dependentModule.issuer = module; const newModule = _this.addModule(dependentModule, cacheGroup); if(!newModule) { // from cache dependentModule = _this.getModule(dependentModule); if(dependentModule.optional) { dependentModule.optional = isOptional(); } iterationDependencies(dependencies); if(_this.profile) { if(!module.profile) { module.profile = {}; } const time = +new Date() - start; if(!module.profile.dependencies || time > module.profile.dependencies) { module.profile.dependencies = time; } } return process.nextTick(callback); } if(newModule instanceof Module) { if(_this.profile) { newModule.profile = dependentModule.profile; } newModule.optional = isOptional(); newModule.issuer = dependentModule.issuer; dependentModule = newModule; iterationDependencies(dependencies); if(_this.profile) { const afterBuilding = +new Date(); module.profile.building = afterBuilding - afterFactory; } if(recursive) { return process.nextTick(_this.processModuleDependencies.bind(_this, dependentModule, callback)); } else { return process.nextTick(callback); } } dependentModule.optional = isOptional(); iterationDependencies(dependencies); _this.buildModule(dependentModule, isOptional(), module, dependencies, err => { if(err) { return errorOrWarningAndCallback(err); } if(_this.profile) { const afterBuilding = +new Date(); dependentModule.profile.building = afterBuilding - afterFactory; } if(recursive) { _this.processModuleDependencies(dependentModule, callback); } else { return callback(); } }); }); }, function finalCallbackAddModuleDependencies(err) { // In V8, the Error objects keep a reference to the functions on the stack. These warnings & // errors are created inside closures that keep a reference to the Compilation, so errors are // leaking the Compilation object. Setting _this to null workarounds the following issue in V8. // https://bugs.chromium.org/p/chromium/issues/detail?id=612191 _this = null; if(err) { return callback(err); } return process.nextTick(callback); }); } _addModuleChain(context, dependency, onModule, callback) { const start = this.profile && +new Date(); const errorAndCallback = this.bail ? function errorAndCallback(err) { callback(err); } : function errorAndCallback(err) { err.dependencies = [dependency]; this.errors.push(err); callback(); }.bind(this); if(typeof dependency !== "object" || dependency === null || !dependency.constructor) { throw new Error("Parameter 'dependency' must be a Dependency"); } const moduleFactory = this.dependencyFactories.get(dependency.constructor); if(!moduleFactory) { throw new Error(`No dependency factory available for this dependency type: ${dependency.constructor.name}`); } moduleFactory.create({ contextInfo: { issuer: "", compiler: this.compiler.name }, context: context, dependencies: [dependency] }, (err, module) => { if(err) { return errorAndCallback(new EntryModuleNotFoundError(err)); } let afterFactory; if(this.profile) { if(!module.profile) { module.profile = {}; } afterFactory = +new Date(); module.profile.factory = afterFactory - start; } const result = this.addModule(module); if(!result) { module = this.getModule(module); onModule(module); if(this.profile) { const afterBuilding = +new Date(); module.profile.building = afterBuilding - afterFactory; } return callback(null, module); } if(result instanceof Module) { if(this.profile) { result.profile = module.profile; } module = result; onModule(module); moduleReady.call(this); return; } onModule(module); this.buildModule(module, false, null, null, (err) => { if(err) { return errorAndCallback(err); } if(this.profile) { const afterBuilding = +new Date(); module.profile.building = afterBuilding - afterFactory; } moduleReady.call(this); }); function moduleReady() { this.processModuleDependencies(module, err => { if(err) { return callback(err); } return callback(null, module); }); } }); } addEntry(context, entry, name, callback) { const slot = { name: name, module: null }; this.preparedChunks.push(slot); this._addModuleChain(context, entry, (module) => { entry.module = module; this.entries.push(module); module.issuer = null; }, (err, module) => { if(err) { return callback(err); } if(module) { slot.module = module; } else { const idx = this.preparedChunks.indexOf(slot); this.preparedChunks.splice(idx, 1); } return callback(); }); } prefetch(context, dependency, callback) { this._addModuleChain(context, dependency, module => { module.prefetched = true; module.issuer = null; }, callback); } rebuildModule(module, thisCallback) { if(module.variables.length || module.blocks.length) throw new Error("Cannot rebuild a complex module with variables or blocks"); if(module.rebuilding) { return module.rebuilding.push(thisCallback); } const rebuilding = module.rebuilding = [thisCallback]; function callback(err) { module.rebuilding = undefined; rebuilding.forEach(cb => cb(err)); } const deps = module.dependencies.slice(); this.buildModule(module, false, module, null, (err) => { if(err) return callback(err); this.processModuleDependencies(module, (err) => { if(err) return callback(err); deps.forEach(d => { if(d.module && d.module.removeReason(module, d)) { module.chunks.forEach(chunk => { if(!d.module.hasReasonForChunk(chunk)) { if(d.module.removeChunk(chunk)) { this.removeChunkFromDependencies(d.module, chunk); } } }); } }); callback(); }); }); } finish() { const modules = this.modules; this.applyPlugins1("finish-modules", modules); for(let index = 0; index < modules.length; index++) { const module = modules[index]; this.reportDependencyErrorsAndWarnings(module, [module]); } } unseal() { this.applyPlugins0("unseal"); this.chunks.length = 0; this.namedChunks = {}; this.additionalChunkAssets.length = 0; this.assets = {}; this.modules.forEach(module => module.unseal()); } seal(callback) { const self = this; self.applyPlugins0("seal"); self.nextFreeModuleIndex = 0; self.nextFreeModuleIndex2 = 0; self.preparedChunks.forEach(preparedChunk => { const module = preparedChunk.module; const chunk = self.addChunk(preparedChunk.name, module); const entrypoint = self.entrypoints[chunk.name] = new Entrypoint(chunk.name); entrypoint.unshiftChunk(chunk); chunk.addModule(module); module.addChunk(chunk); chunk.entryModule = module; self.assignIndex(module); self.assignDepth(module); self.processDependenciesBlockForChunk(module, chunk); }); self.sortModules(self.modules); self.applyPlugins0("optimize"); while(self.applyPluginsBailResult1("optimize-modules-basic", self.modules) || self.applyPluginsBailResult1("optimize-modules", self.modules) || self.applyPluginsBailResult1("optimize-modules-advanced", self.modules)); // eslint-disable-line no-extra-semi self.applyPlugins1("after-optimize-modules", self.modules); while(self.applyPluginsBailResult1("optimize-chunks-basic", self.chunks) || self.applyPluginsBailResult1("optimize-chunks", self.chunks) || self.applyPluginsBailResult1("optimize-chunks-advanced", self.chunks)); // eslint-disable-line no-extra-semi self.applyPlugins1("after-optimize-chunks", self.chunks); self.applyPluginsAsyncSeries("optimize-tree", self.chunks, self.modules, function sealPart2(err) { if(err) { return callback(err); } self.applyPlugins2("after-optimize-tree", self.chunks, self.modules); const shouldRecord = self.applyPluginsBailResult("should-record") !== false; self.applyPlugins2("revive-modules", self.modules, self.records); self.applyPlugins1("optimize-module-order", self.modules); self.applyPlugins1("advanced-optimize-module-order", self.modules); self.applyPlugins1("before-module-ids", self.modules); self.applyPlugins1("module-ids", self.modules); self.applyModuleIds(); self.applyPlugins1("optimize-module-ids", self.modules); self.applyPlugins1("after-optimize-module-ids", self.modules); self.sortItemsWithModuleIds(); self.applyPlugins2("revive-chunks", self.chunks, self.records); self.applyPlugins1("optimize-chunk-order", self.chunks); self.applyPlugins1("before-chunk-ids", self.chunks); self.applyChunkIds(); self.applyPlugins1("optimize-chunk-ids", self.chunks); self.applyPlugins1("after-optimize-chunk-ids", self.chunks); self.sortItemsWithChunkIds(); if(shouldRecord) self.applyPlugins2("record-modules", self.modules, self.records); if(shouldRecord) self.applyPlugins2("record-chunks", self.chunks, self.records); self.applyPlugins0("before-hash"); self.createHash(); self.applyPlugins0("after-hash"); if(shouldRecord) self.applyPlugins1("record-hash", self.records); self.applyPlugins0("before-module-assets"); self.createModuleAssets(); if(self.applyPluginsBailResult("should-generate-chunk-assets") !== false) { self.applyPlugins0("before-chunk-assets"); self.createChunkAssets(); } self.applyPlugins1("additional-chunk-assets", self.chunks); self.summarizeDependencies(); if(shouldRecord) self.applyPlugins2("record", self, self.records); self.applyPluginsAsync("additional-assets", err => { if(err) { return callback(err); } self.applyPluginsAsync("optimize-chunk-assets", self.chunks, err => { if(err) { return callback(err); } self.applyPlugins1("after-optimize-chunk-assets", self.chunks); self.applyPluginsAsync("optimize-assets", self.assets, err => { if(err) { return callback(err); } self.applyPlugins1("after-optimize-assets", self.assets); if(self.applyPluginsBailResult("need-additional-seal")) { self.unseal(); return self.seal(callback); } return self.applyPluginsAsync("after-seal", callback); }); }); }); }); } sortModules(modules) { modules.sort((a, b) => { if(a.index < b.index) return -1; if(a.index > b.index) return 1; return 0; }); } reportDependencyErrorsAndWarnings(module, blocks) { for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { const block = blocks[indexBlock]; const dependencies = block.dependencies; for(let indexDep = 0; indexDep < dependencies.length; indexDep++) { const d = dependencies[indexDep]; const warnings = d.getWarnings(); if(warnings) { for(let indexWar = 0; indexWar < warnings.length; indexWar++) { const w = warnings[indexWar]; const warning = new ModuleDependencyWarning(module, w, d.loc); this.warnings.push(warning); } } const errors = d.getErrors(); if(errors) { for(let indexErr = 0; indexErr < errors.length; indexErr++) { const e = errors[indexErr]; const error = new ModuleDependencyError(module, e, d.loc); this.errors.push(error); } } } this.reportDependencyErrorsAndWarnings(module, block.blocks); } } addChunk(name, module, loc) { if(name) { if(Object.prototype.hasOwnProperty.call(this.namedChunks, name)) { const chunk = this.namedChunks[name]; if(module) { chunk.addOrigin(module, loc); } return chunk; } } const chunk = new Chunk(name, module, loc); this.chunks.push(chunk); if(name) { this.namedChunks[name] = chunk; } return chunk; } assignIndex(module) { const _this = this; const queue = [() => { assignIndexToModule(module); }]; const iteratorAllDependencies = d => { queue.push(() => assignIndexToDependency(d)); }; function assignIndexToModule(module) { // enter module if(typeof module.index !== "number") { module.index = _this.nextFreeModuleIndex++; // leave module queue.push(() => module.index2 = _this.nextFreeModuleIndex2++); // enter it as block assignIndexToDependencyBlock(module); } } function assignIndexToDependency(dependency) { if(dependency.module) { queue.push(() => assignIndexToModule(dependency.module)); } } function assignIndexToDependencyBlock(block) { let allDependencies = []; function iteratorDependency(d) { allDependencies.push(d); } function iteratorBlock(b) { queue.push(() => assignIndexToDependencyBlock(b)); } if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.blocks) { const blocks = block.blocks; let indexBlock = blocks.length; while(indexBlock--) { iteratorBlock(blocks[indexBlock]); } } let indexAll = allDependencies.length; while(indexAll--) { iteratorAllDependencies(allDependencies[indexAll]); } } while(queue.length) { queue.pop()(); } } assignDepth(module) { function assignDepthToModule(module, depth) { // enter module if(typeof module.depth === "number" && module.depth <= depth) return; module.depth = depth; // enter it as block assignDepthToDependencyBlock(module, depth + 1); } function assignDepthToDependency(dependency, depth) { if(dependency.module) { queue.push(() => assignDepthToModule(dependency.module, depth)); } } function assignDepthToDependencyBlock(block, depth) { function iteratorDependency(d) { assignDepthToDependency(d, depth); } function iteratorBlock(b) { assignDepthToDependencyBlock(b, depth); } if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.blocks) { iterationOfArrayCallback(block.blocks, iteratorBlock); } } const queue = [() => { assignDepthToModule(module, 0); }]; while(queue.length) { queue.pop()(); } } processDependenciesBlockForChunk(block, chunk) { const iteratorBlock = b => { let c; if(!b.chunks) { c = this.addChunk(b.chunkName, b.module, b.loc); b.chunks = [c]; c.addBlock(b); } else { c = b.chunks[0]; } chunk.addChunk(c); c.addParent(chunk); queue.push([b, c]); }; const iteratorDependency = d => { if(!d.module) { return; } if(d.weak) { return; } if(chunk.addModule(d.module)) { d.module.addChunk(chunk); queue.push([d.module, chunk]); } }; const queue = [ [block, chunk] ]; while(queue.length) { const queueItem = queue.pop(); block = queueItem[0]; chunk = queueItem[1]; if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.blocks) { iterationOfArrayCallback(block.blocks, iteratorBlock); } } } removeChunkFromDependencies(block, chunk) { const iteratorDependency = d => { if(!d.module) { return; } if(!d.module.hasReasonForChunk(chunk)) { if(d.module.removeChunk(chunk)) { this.removeChunkFromDependencies(d.module, chunk); } } }; const blocks = block.blocks; for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { const chunks = blocks[indexBlock].chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const blockChunk = chunks[indexChunk]; chunk.removeChunk(blockChunk); blockChunk.removeParent(chunk); this.removeChunkFromDependencies(chunks, blockChunk); } } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } } applyModuleIds() { let unusedIds = []; let nextFreeModuleId = 0; let usedIds = []; // TODO consider Map when performance has improved https://gist.github.com/sokra/234c077e1299b7369461f1708519c392 const usedIdMap = Object.create(null); if(this.usedModuleIds) { Object.keys(this.usedModuleIds).forEach(key => { const id = this.usedModuleIds[key]; if(!usedIdMap[id]) { usedIds.push(id); usedIdMap[id] = true; } }); } const modules1 = this.modules; for(let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { const module1 = modules1[indexModule1]; if(module1.id && !usedIdMap[module1.id]) { usedIds.push(module1.id); usedIdMap[module1.id] = true; } } if(usedIds.length > 0) { let usedIdMax = -1; for(let index = 0; index < usedIds.length; index++) { const usedIdKey = usedIds[index]; if(typeof usedIdKey !== "number") { continue; } usedIdMax = Math.max(usedIdMax, usedIdKey); } let lengthFreeModules = nextFreeModuleId = usedIdMax + 1; while(lengthFreeModules--) { if(!usedIdMap[lengthFreeModules]) { unusedIds.push(lengthFreeModules); } } } const modules2 = this.modules; for(let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { const module2 = modules2[indexModule2]; if(module2.id === null) { if(unusedIds.length > 0) module2.id = unusedIds.pop(); else module2.id = nextFreeModuleId++; } } } applyChunkIds() { const unusedIds = []; let nextFreeChunkId = 0; function getNextFreeChunkId(usedChunkIds) { const keyChunks = Object.keys(usedChunkIds); let result = -1; for(let index = 0; index < keyChunks.length; index++) { const usedIdKey = keyChunks[index]; const usedIdValue = usedChunkIds[usedIdKey]; if(typeof usedIdValue !== "number") { continue; } result = Math.max(result, usedIdValue); } return result; } if(this.usedChunkIds) { nextFreeChunkId = getNextFreeChunkId(this.usedChunkIds) + 1; let index = nextFreeChunkId; while(index--) { if(this.usedChunkIds[index] !== index) { unusedIds.push(index); } } } const chunks = this.chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; if(chunk.id === null) { if(unusedIds.length > 0) chunk.id = unusedIds.pop(); else chunk.id = nextFreeChunkId++; } if(!chunk.ids) { chunk.ids = [chunk.id]; } } } sortItemsWithModuleIds() { this.modules.sort(byId); const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { modules[indexModule].sortItems(); } const chunks = this.chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { chunks[indexChunk].sortItems(); } } sortItemsWithChunkIds() { this.chunks.sort(byId); const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { modules[indexModule].sortItems(); } const chunks = this.chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { chunks[indexChunk].sortItems(); } } summarizeDependencies() { function filterDups(array) { const newArray = []; for(let i = 0; i < array.length; i++) { if(i === 0 || array[i - 1] !== array[i]) newArray.push(array[i]); } return newArray; } this.fileDependencies = (this.compilationDependencies || []).slice(); this.contextDependencies = []; this.missingDependencies = []; const children = this.children; for(let indexChildren = 0; indexChildren < children.length; indexChildren++) { const child = children[indexChildren]; this.fileDependencies = this.fileDependencies.concat(child.fileDependencies); this.contextDependencies = this.contextDependencies.concat(child.contextDependencies); this.missingDependencies = this.missingDependencies.concat(child.missingDependencies); } const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { const module = modules[indexModule]; if(module.fileDependencies) { const fileDependencies = module.fileDependencies; for(let indexFileDep = 0; indexFileDep < fileDependencies.length; indexFileDep++) { this.fileDependencies.push(fileDependencies[indexFileDep]); } } if(module.contextDependencies) { const contextDependencies = module.contextDependencies; for(let indexContextDep = 0; indexContextDep < contextDependencies.length; indexContextDep++) { this.contextDependencies.push(contextDependencies[indexContextDep]); } } } this.errors.forEach(error => { if(Array.isArray(error.missing)) { error.missing.forEach(item => this.missingDependencies.push(item)); } }); this.fileDependencies.sort(); this.fileDependencies = filterDups(this.fileDependencies); this.contextDependencies.sort(); this.contextDependencies = filterDups(this.contextDependencies); this.missingDependencies.sort(); this.missingDependencies = filterDups(this.missingDependencies); } createHash() { const outputOptions = this.outputOptions; const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = crypto.createHash(hashFunction); if(outputOptions.hashSalt) hash.update(outputOptions.hashSalt); this.mainTemplate.updateHash(hash); this.chunkTemplate.updateHash(hash); this.moduleTemplate.updateHash(hash); this.children.forEach(function(child) { hash.update(child.hash); }); // clone needed as sort below is inplace mutation const chunks = this.chunks.slice(); /** * sort here will bring all "falsy" values to the beginning * this is needed as the "hasRuntime()" chunks are dependent on the * hashes of the non-runtime chunks. */ chunks.sort((a, b) => { const aEntry = a.hasRuntime(); const bEntry = b.hasRuntime(); if(aEntry && !bEntry) return 1; if(!aEntry && bEntry) return -1; return 0; }); for(let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const chunkHash = crypto.createHash(hashFunction); if(outputOptions.hashSalt) chunkHash.update(outputOptions.hashSalt); chunk.updateHash(chunkHash); if(chunk.hasRuntime()) { this.mainTemplate.updateHashForChunk(chunkHash, chunk); } else { this.chunkTemplate.updateHashForChunk(chunkHash, chunk); } this.applyPlugins2("chunk-hash", chunk, chunkHash); chunk.hash = chunkHash.digest(hashDigest); hash.update(chunk.hash); chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); } this.fullHash = hash.digest(hashDigest); this.hash = this.fullHash.substr(0, hashDigestLength); } modifyHash(update) { const outputOptions = this.outputOptions; const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = crypto.createHash(hashFunction); hash.update(this.fullHash); hash.update(update); this.fullHash = hash.digest(hashDigest); this.hash = this.fullHash.substr(0, hashDigestLength); } createModuleAssets() { for(let i = 0; i < this.modules.length; i++) { const module = this.modules[i]; if(module.assets) { Object.keys(module.assets).forEach((assetName) => { const fileName = this.getPath(assetName); this.assets[fileName] = module.assets[assetName]; this.applyPlugins2("module-asset", module, fileName); }); } } } createChunkAssets() { const outputOptions = this.outputOptions; const filename = outputOptions.filename; const chunkFilename = outputOptions.chunkFilename; for(let i = 0; i < this.chunks.length; i++) { const chunk = this.chunks[i]; chunk.files = []; const chunkHash = chunk.hash; let source; let file; const filenameTemplate = chunk.filenameTemplate ? chunk.filenameTemplate : chunk.isInitial() ? filename : chunkFilename; try { const useChunkHash = !chunk.hasRuntime() || (this.mainTemplate.useChunkHash && this.mainTemplate.useChunkHash(chunk)); const usedHash = useChunkHash ? chunkHash : this.fullHash; const cacheName = "c" + chunk.id; if(this.cache && this.cache[cacheName] && this.cache[cacheName].hash === usedHash) { source = this.cache[cacheName].source; } else { if(chunk.hasRuntime()) { source = this.mainTemplate.render(this.hash, chunk, this.moduleTemplate, this.dependencyTemplates); } else { source = this.chunkTemplate.render(chunk, this.moduleTemplate, this.dependencyTemplates); } if(this.cache) { this.cache[cacheName] = { hash: usedHash, source: source = (source instanceof CachedSource ? source : new CachedSource(source)) }; } } file = this.getPath(filenameTemplate, { noChunkHash: !useChunkHash, chunk }); if(this.assets[file]) throw new Error(`Conflict: Multiple assets emit to the same filename ${file}`); this.assets[file] = source; chunk.files.push(file); this.applyPlugins2("chunk-asset", chunk, file); } catch(err) { this.errors.push(new ChunkRenderError(chunk, file || filenameTemplate, err)); } } } getPath(filename, data) { data = data || {}; data.hash = data.hash || this.hash; return this.mainTemplate.applyPluginsWaterfall("asset-path", filename, data); } getStats() { return new Stats(this); } createChildCompiler(name, outputOptions) { return this.compiler.createChildCompiler(this, name, outputOptions); } checkConstraints() { const usedIds = {}; const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { const moduleId = modules[indexModule].id; if(usedIds[moduleId]) throw new Error(`checkConstraints: duplicate module id ${moduleId}`); } const chunks = this.chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; if(chunks.indexOf(chunk) !== indexChunk) throw new Error(`checkConstraints: duplicate chunk in compilation ${chunk.debugId}`); chunk.checkConstraints(); } } } module.exports = Compilation;
const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; var engine, world, backgroundImg; var canvas, angle, tower, ground, cannon; var balls = []; var boats = []; var boatAnimation = []; var boatSpriteData; var boatSpriteSheet; var score = 0; function preload() { backgroundImg = loadImage("./assets/background.gif"); towerImage = loadImage("./assets/tower.png"); boatSpriteData = loadJSON ("./assets/boat/boat.json") boatSpriteSheet = loadImage("./assets/boat/boat.png") } function setup() { canvas = createCanvas(1200, 600); engine = Engine.create(); world = engine.world; angleMode(DEGREES) angle = 15 ground = Bodies.rectangle(0, height - 1, width * 2, 1, { isStatic: true }); World.add(world, ground); tower = Bodies.rectangle(160, 350, 160, 310, { isStatic: true }); World.add(world, tower); cannon = new Cannon(180, 110, 130, 100, angle); var boatFrames = boatSpriteData.frames; for(var i = 0; i < boatFrames.length; i++){ var pos = boatFrames[i].position; var img = boatSpriteSheet.get(pos.x, pos.y, pos.w, pos.h); boatAnimation.push(img); } } function draw() { background(189); image(backgroundImg, 0, 0, width, height); Engine.update(engine); push(); translate(ground.position.x, ground.position.y); fill("brown"); rectMode(CENTER); rect(0, 0, width * 2, 1); pop(); push(); translate(tower.position.x, tower.position.y); rotate(tower.angle); imageMode(CENTER); image(towerImage, 0, 0, 160, 310); pop(); showBoats(); for (var i = 0; i < balls.length; i++) { showCannonBalls(balls[i], i); collisionWithBoat(i); } cannon.display(); } function collisionWithBoat(index) { for (var i = 0; i < boats.length; i++) { if (balls[index] !== undefined && boats[i] !== undefined) { var collision = Matter.SAT.collides(balls[index].body, boats[i].body); if (collision.collided) { boats[i].remove(i); Matter.World.remove(world, balls[index].body); delete balls[index]; } } } } function keyPressed() { if (keyCode === DOWN_ARROW) { var cannonBall = new CannonBall(cannon.x, cannon.y); cannonBall.trajectory = []; Matter.Body.setAngle(cannonBall.body, cannon.angle); balls.push(cannonBall); } } function showCannonBalls(ball, index) { if (ball) { ball.display(); if (ball.body.position.x >= width || ball.body.position.y >= height - 50) { ball.remove(index); } } } function showBoats() { if (boats.length > 0) { if ( boats[boats.length - 1] === undefined || boats[boats.length - 1].body.position.x < width - 300 ) { var positions = [-40, -60, -70, -20]; var position = random(positions); var boat = new Boat(width, height - 100, 170, 170, position, boatAnimation); boats.push(boat); } for (var i = 0; i < boats.length; i++) { if (boats[i]) { Matter.Body.setVelocity(boats[i].body, { x: -0.9, y: 0 }); boats[i].display(); boats[i].animate(); } else { boats[i]; } } } else { var boat = new Boat(width, height - 60, 170, 170, -60, boatAnimation); boats.push(boat); } } function keyReleased() { if (keyCode === DOWN_ARROW) { balls[balls.length - 1].shoot(); } }
'use strict'; (function() { function getCookieValue(name, defaultValue) { var value = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)'); return value ? value.pop() : defaultValue; } function showHeader(visible) { if (bannerVisible === visible) { return; } const body = document.querySelector('body.devsite-landing-page'); if (!body) { return; } if (visible === true) { body.querySelector('.devsite-wrapper') .style.marginTop = navHeadHeight + 'px'; body.querySelector('header.devsite-top-section') .classList.remove('devsite-top-section-pinned'); body.querySelector('.devsite-top-logo-row-wrapper-wrapper') .style.position = 'fixed'; body.querySelector('.devsite-collapsible-section') .style.marginTop = '0px'; } else { body.querySelector('.devsite-wrapper') .style.marginTop = (navHeadHeight + bannerHeight) + 'px'; body.querySelector('header.devsite-top-section') .classList.add('devsite-top-section-pinned'); body.querySelector('.devsite-top-logo-row-wrapper-wrapper') .style.position = 'relative'; body.querySelector('.devsite-collapsible-section') .style.marginTop = '-190px'; } bannerVisible = visible; } function initNavToggles() { var elems = document .querySelectorAll('.devsite-section-nav .devsite-nav-item-section-expandable'); elems.forEach(function(elem) { var span = elem.querySelector('span'); span.addEventListener('click', toggleNav); var link = elem.querySelector('a.devsite-nav-toggle'); link.addEventListener('click', toggleNav); }); } function initLangSelector() { var currentLang = getCookieValue('hl'); var langSelector = document.querySelector('#langSelector'); var langOptions = langSelector.querySelectorAll('option'); langOptions.forEach(function(opt) { if (opt.value === currentLang) { opt.setAttribute('selected', true); } }); langSelector.addEventListener('change', function(evt) { var newLang = langSelector.selectedOptions[0].value; var newUrl = window.location.origin + window.location.pathname; newUrl += '?hl=' + newLang; newUrl += window.location.hash; window.location = newUrl; }); } /* Expand/Collapses the Primary Left Hand Nav */ function toggleNav(event) { var srcElement = event.srcElement || event.target; var srcParent = srcElement.parentElement; // Ensure's we're in the outer most <span> if (srcElement.localName === 'span' && srcParent.localName === 'span') { srcElement = srcElement.parentElement; srcParent = srcElement.parentElement; } // Grabs the anchor and the UL so we can update them var anchor = srcParent.querySelector('a.devsite-nav-toggle'); var ul = srcParent.querySelector('ul.devsite-nav-section'); // Toggles the expanded/collapsed classes anchor.classList.toggle('devsite-nav-toggle-expanded'); anchor.classList.toggle('devsite-nav-toggle-collapsed'); ul.classList.toggle('devsite-nav-section-collapsed'); ul.classList.toggle('devsite-nav-section-expanded'); } function highlightActiveNavElement() { var elems = document.querySelectorAll('.devsite-section-nav a.devsite-nav-title'); var currentURL = window.location.pathname; for (var i = 0; i < elems.length; i++) { var elem = elems[i]; if (currentURL === elem.getAttribute('href')) { var parentLI = elem.parentElement; if (parentLI.localName === 'li') { parentLI.classList.add('devsite-nav-active'); expandPathAndHighlight(parentLI); break; } } } } function expandPathAndHighlight(elem) { // Walks up the tree from the current element and expands all tree nodes var parent = elem.parentElement; var parentIsCollapsed = parent.classList.contains('devsite-nav-section-collapsed'); if (parent.localName === 'ul' && parentIsCollapsed) { parent.classList.toggle('devsite-nav-section-collapsed'); parent.classList.toggle('devsite-nav-section-expanded'); // Checks if the grandparent is an expandable element var grandParent = parent.parentElement; var grandParentIsExpandable = grandParent.classList.contains('devsite-nav-item-section-expandable'); if (grandParent.localName === 'li' && grandParentIsExpandable) { var anchor = grandParent.querySelector('a.devsite-nav-toggle'); anchor.classList.toggle('devsite-nav-toggle-expanded'); anchor.classList.toggle('devsite-nav-toggle-collapsed'); expandPathAndHighlight(grandParent); } } } function initYouTubeVideos() { var videoElements = document.querySelectorAll('iframe.devsite-embedded-youtube-video'); videoElements.forEach(function(elem) { var videoID = elem.getAttribute('data-video-id'); if (videoID) { var videoURL = 'https://www.youtube.com/embed/' + videoID; videoURL += '?autohide=1&amp;showinfo=0&amp;enablejsapi=1'; elem.src = videoURL; } }); } function initFeed() { var placeholderTitle = 'RSS Feed Widget is not supported.'; var placeholderText = 'The RSS Feed Widget is <b>NOT</b> supported in the '; placeholderText += 'local development environment. Sorry. '; placeholderText += 'Lorem ipsum dolor sit amet, perfecto volutpat prodesset duo ei. Per ne albucius consulatu. Graece repudiandae ut vis. Quot omnis vix ad, prodesset consetetur persequeris ea mel. Nostrum urbanitas usu eu, qui id graeci facilisi.'; var feedElements = document.querySelectorAll('div.feed.hfeed:not(.rendered)'); feedElements.forEach(function(elem) { elem.querySelector('article.hentry').style.display = 'block'; elem.querySelector('header').textContent = placeholderTitle; elem.querySelector('.entry-content').innerHTML = placeholderText; elem.querySelector('.published').textContent = 'January 1st, 2016'; }); } initNavToggles(); highlightActiveNavElement(); initYouTubeVideos(); initFeed(); initLangSelector(); let bannerVisible = true; const navHeadHeight = 48; const bannerHeight = document.querySelector('header.devsite-top-section') .clientHeight; window.addEventListener('scroll', function(e) { if (window.scrollY > bannerHeight) { showHeader(false); } else if (window.scrollY < bannerHeight) { showHeader(true); } }); })();
import React from 'react' import {connect} from 'react-redux' import {authenticate} from '../store' /** * COMPONENT */ const AuthForm = props => { const {name, displayName, handleSubmit, error} = props return ( <div> <form onSubmit={handleSubmit} name={name}> <div> <label htmlFor="email"> <small>Email</small> </label> <input name="email" type="text" /> </div> <div> <label htmlFor="password"> <small>Password</small> </label> <input name="password" type="password" /> </div> <div> <button type="submit">{displayName}</button> </div> {error && error.response && <div> {error.response.data} </div>} </form> </div> ) } /** * CONTAINER * Note that we have two different sets of 'mapStateToProps' functions - * one for Login, and one for Signup. However, they share the same 'mapDispatchToProps' * function, and share the same Component. This is a good example of how we * can stay DRY with interfaces that are very similar to each other! */ const mapLogin = state => { return { name: 'login', displayName: 'Login', error: state.auth.error } } const mapSignup = state => { return { name: 'signup', displayName: 'Sign Up', error: state.auth.error } } const mapDispatch = dispatch => { return { handleSubmit(evt) { evt.preventDefault() const formName = evt.target.name const email = evt.target.email.value const password = evt.target.password.value dispatch(authenticate(email, password, formName)) } } } export const Login = connect(mapLogin, mapDispatch)(AuthForm) export const Signup = connect(mapSignup, mapDispatch)(AuthForm)
import DEFAULTS from '/modules/mmi/scripts/defaults.js'; import MMI, { validate, SourceFactory } from '/modules/mmi/scripts/main.js'; import DeckConfigApplication from '/modules/mmi/scripts/apps/DeckConfigApplication.js'; /** * Form application to configure settings of the Deck. */ export default class SourceConfigApplication extends FormApplication { constructor(object={}, options={}) { super(object); } static get defaultOptions() { return mergeObject(super.defaultOptions, { title: 'Mildly Magical Inspiration - Source Configuration', id: "source-config", template: './' + DEFAULTS.templatePath + '/source-config.html', width: 800, height: "auto", closeOnSubmit: false, submitOnChange: false }) } getData(options) { return mergeObject(super.getData().object, { sources: MMI.sources }); } async activateListeners(html) { super.activateListeners(html); html.on('click', 'a.source-control', async (event) => { const sourceId = $(event.target).parent().prop('id'); const actionType = $(event.target).parents('a.source-control').data('action') || $(event.target).data('action'); switch(actionType) { case 'add': this.addSource(); break; case 'edit': this.openSource(sourceId); break; case 'delete': this.deleteSource(sourceId) break; } }); this.markActive(html); } markActive(html) { const activeSource = html.find('ul.source-list li.isActive label'); const newEl = $('<span></span>'); newEl.css('font-weight', 'bold'); newEl.css('font-style', 'italic'); newEl.text(` (Curently Active)`); activeSource.append(newEl); } addSource() { MMI.makeDialog({ title: 'Add a new Source', content: `<p>To use a pre-existing source upload a source-file from your harddrive. The uploader only accepts JSON-files!</p>`, form: { name: 'MMI-NewSourceUpload', type: 'file', options: { accept: '.json' } }, buttons: { fromFile: { icon: 'fa-file-import', label: 'Create Source from File', callback: async () => { this.createFromFile($('input[name=MMI-NewSourceUpload]').prop('files')[0]) } }, newSource: { icon: 'fa-forward', label: 'Skip Uploader', callback: () => { this.createSource() } } }, def: 'newSource', render: html => { MMI.disableOnEmpty({ target: html.find('button.fromFile'), operator: html.find('input[name="MMI-NewSourceUpload"]') }) } }) } async createFromFile(fileData) { const fileName = fileData.name.split('.'); fileName.pop(); const fileContent = await readTextFromFile(fileData); let valJSON; if(validate.json(fileContent)) valJSON = JSON.parse(fileContent); const validated = validate.source(valJSON); if(validated) { if(!validated.title) validated.title = fileName.join(' '); this.createSource(validated); } } async createSource(data = { title: 'New Source' }) { const newSource = await SourceFactory.create(data); this.openSource(newSource._id); } openSource(sourceId) { new DeckConfigApplication({ sourceId }).render(true); } async deleteSource(sourceId) { const source = MMI.getSource(sourceId); MMI.makeDialog({ title: `Delete Source: ${ source.title }`, content: `<p>Are you sure you want to delete the source <em>${ source.title }</em>?</p>`, buttons: { delete: { icon: 'fa-check', label: 'Delete Source', callback: async () => { await SourceFactory.removeSource(sourceId); } } } }) } async _updateObject(event, formData) { // } }
import React from 'react'; import Home from "modules/home/Home.js"; import 'App.scss'; const App = () => ( <Home /> ) export default App;
/* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const { PostgreSQLManagementFlexibleServerClient } = require("@azure/arm-postgresql-flexible"); const { DefaultAzureCredential } = require("@azure/identity"); /** * This sample demonstrates how to List all the configurations in a given server. * * @summary List all the configurations in a given server. * x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2021-06-01/examples/ConfigurationListByServer.json */ async function configurationList() { const subscriptionId = "ffffffff-ffff-ffff-ffff-ffffffffffff"; const resourceGroupName = "testrg"; const serverName = "testserver"; const credential = new DefaultAzureCredential(); const client = new PostgreSQLManagementFlexibleServerClient(credential, subscriptionId); const resArray = new Array(); for await (let item of client.configurations.listByServer(resourceGroupName, serverName)) { resArray.push(item); } console.log(resArray); } configurationList().catch(console.error);
/*----------ws License and Copyright Notices-------- ws http://einaros.github.com/ws ----------------------------------- This file is based on or incorporates material from the projects listed below (collectively, “Third Party Code”). Microsoft is not the original author of the Third Party Code. The original copyright notice and the MIT license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms of the Microsoft Reference Source Code License set forth below. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise. ---------------------------------------- ws: a node.js websocket client Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> http://einaros.github.com/ws Portions Copyright Microsoft Open Technologies, Inc. --------------------------------------- Copyright 2012 Microsoft Open Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------- Provided for Informational Purposes Only MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --End of ws Licenses and Copyright Notices------*/ var util = require('util') , events = require('events') , http = require('http') , crypto = require('crypto') , url = require('url') , Options = require('options') , WebSocket = require('./WebSocket') , tls = require('tls') , url = require('url') , SMSession = require('./SMSession'); /** * WebSocket implementation */ function WebSocketServer(options, callback) { options = new Options({ host: '127.0.0.1', port: null, server: null, verifyClient: null, path: null, noServer: false, disableHixie: false, clientTracking: true }).merge(options); if (!options.value.port && !options.value.server && !options.value.noServer) { throw new TypeError('`port` or a `server` must be provided'); } var self = this; if (options.value.port) { Object.defineProperty(this, '_server', { configurable: true, value: http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Speed+Mobility Server! Please use SM client to connect.'); }) }); this._server.listen(options.value.port, options.value.host || '127.0.0.1', callback); Object.defineProperty(this, '_closeServer', { value: function() { self._server.close(); } }); } else if (options.value.server) { Object.defineProperty(this, '_server', { value: options.value.server, configurable: true }); if (options.value.path) { // take note of the path, to avoid collisions when multiple websocket servers are // listening on the same http server if (this._server._webSocketPaths && options.value.server._webSocketPaths[options.value.path]) { throw new Error('two instances of WebSocketServer cannot listen on the same http server path'); } if (typeof this._server._webSocketPaths !== 'object') { Object.defineProperty(this._server, '_webSocketPaths', { value: {}, configurable: true }); } this._server._webSocketPaths[options.value.path] = 1; } } if (typeof this._server != 'undefined') { this._server.on('error', function(error) { self.emit('error', error) }); this._server.on('upgrade', function(req, socket, upgradeHead) { self.handleUpgrade(req, socket, upgradeHead, function(client) { self.emit('connection', client); }); }); } Object.defineProperty(this, 'options', { value: options.value }); Object.defineProperty(this, 'path', { value: options.value.path }); Object.defineProperty(this, '_clients', { value: [] }); Object.defineProperty(this, 'clients', { get: function() { return self._clients; } }); } /** * Inherits from EventEmitter. */ util.inherits(WebSocketServer, events.EventEmitter); /** * Immediately shuts down the connection. * * @api public */ WebSocketServer.prototype.close = function(code, data) { // terminate all associated clients var error = null; try { for (var i = 0, l = this._clients.length; i < l; ++i) { this._clients[i].terminate(); } } catch (e) { error = e; } // remove path descriptor, if any if (this.path && this._server._webSocketPaths) { delete this._server._webSocketPaths[this.path]; if (Object.keys(this._server._webSocketPaths).length == 0) { delete this._server._webSocketPaths; } } // close the http server if it was internally created try { if (typeof this._closeServer !== 'undefined') { this._closeServer(); } } finally { delete this._server; } if (error) throw error; } /** * Handle a HTTP Upgrade request. * * @api public */ WebSocketServer.prototype.handleUpgrade = function(req, socket, upgradeHead, cb) { // check for wrong path if (this.options.path) { var u = url.parse(req.url); if (u && u.pathname !== this.options.path) return; } if (typeof req.headers.upgrade === 'undefined' || req.headers.upgrade.toLowerCase() !== 'websocket') { abortConnection(socket, 400, 'Bad Request'); return; } if (req.headers['sec-websocket-key1']) handleHixieUpgrade.apply(this, arguments); else handleHybiUpgrade.apply(this, arguments); } module.exports = WebSocketServer; /** * Entirely private apis, * which may or may not be bound to a sepcific WebSocket instance. */ function handleHybiUpgrade(req, socket, upgradeHead, cb) { // verify key presence if (!req.headers['sec-websocket-key']) { abortConnection(socket, 400, 'Bad Request'); return; } // verify version var version = parseInt(req.headers['sec-websocket-version']); if ([8, 13].indexOf(version) === -1) { abortConnection(socket, 400, 'Bad Request'); return; } // verify client var origin = version < 13 ? req.headers['sec-websocket-origin'] : req.headers['origin']; var args = [req, socket, upgradeHead, version, cb]; if (typeof this.options.verifyClient == 'function') { var info = { origin: origin, secure: typeof req.connection.encrypted !== 'undefined', req: req }; if (this.options.verifyClient.length == 2) { var self = this; this.options.verifyClient(info, function(result) { if (!result) abortConnection(socket, 401, 'Unauthorized') else completeUpgrade.apply(self, args); }); return; } else if (!this.options.verifyClient(info)) { abortConnection(socket, 401, 'Unauthorized'); return; } } completeUpgrade.apply(this, args); } function completeUpgrade(req, socket, upgradeHead, version, cb) { var protocol = req.headers['sec-websocket-protocol']; // calc key var key = req.headers['sec-websocket-key']; var shasum = crypto.createHash('sha1'); shasum.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); key = shasum.digest('base64'); var headers = [ 'HTTP/1.1 101 Switching Protocols' , 'Upgrade: websocket' , 'Connection: Upgrade' , 'Sec-WebSocket-Accept: ' + key ]; if (typeof protocol != 'undefined') { headers['Sec-WebSocket-Protocol'] = protocol; } try { socket.write(headers.concat('', '').join('\r\n')); } catch (e) { try { socket.end(); } catch (_) {} return; } socket.setTimeout(0); socket.setNoDelay(true); var client = new SMSession([req, socket, upgradeHead], { protocolVersion: version, protocol: protocol }); if (this.options.clientTracking) { this._clients.push(client); var self = this; client.on('close', function() { var index = self._clients.indexOf(client); if (index != -1) { self._clients.splice(index, 1); } }); } cb(client); } function handleHixieUpgrade(req, socket, upgradeHead, cb) { if (this.options.disableHixie) { abortConnection(socket, 401, 'Hixie support disabled'); return; } // verify key presence if (!req.headers['sec-websocket-key2']) { abortConnection(socket, 400, 'Bad Request'); return; } // setup handshake completion to run after client has been verified var self = this; var onClientVerified = function() { var protocol = req.headers['sec-websocket-protocol']; // handshake completion code to run once nonce has been successfully retrieved var completeHandshake = function(nonce, rest) { // calculate key var k1 = req.headers['sec-websocket-key1'] , k2 = req.headers['sec-websocket-key2'] , md5 = crypto.createHash('md5'); [k1, k2].forEach(function (k) { var n = parseInt(k.replace(/[^\d]/g, '')) , spaces = k.replace(/[^ ]/g, '').length; if (spaces === 0 || n % spaces !== 0){ abortConnection(socket, 400, 'Bad Request'); return; } n /= spaces; md5.update(String.fromCharCode( n >> 24 & 0xFF, n >> 16 & 0xFF, n >> 8 & 0xFF, n & 0xFF)); }); md5.update(nonce.toString('binary')); var headers = [ 'HTTP/1.1 101 Switching Protocols' , 'Upgrade: WebSocket' , 'Connection: Upgrade' , 'Sec-WebSocket-Location: ' + location ]; if (typeof protocol != 'undefined') headers.push('Sec-WebSocket-Protocol: ' + protocol); if (typeof origin != 'undefined') headers.push('Sec-WebSocket-Origin: ' + origin); socket.setTimeout(0); socket.setNoDelay(true); try { socket.write(headers.concat('', '').join('\r\n')); socket.write(md5.digest('binary'), 'binary'); } catch (e) { try { socket.end(); } catch (_) {} return; } var client = new WebSocket([req, socket, rest], { protocolVersion: 'hixie-76', protocol: protocol }); if (this.options.clientTracking) { self._clients.push(client); client.on('close', function() { var index = self._clients.indexOf(client); if (index != -1) { self._clients.splice(index, 1); } }); } cb(client); } // retrieve nonce var nonceLength = 8; if (upgradeHead && upgradeHead.length >= nonceLength) { var nonce = upgradeHead.slice(0, nonceLength); var rest = upgradeHead.length > nonceLength ? upgradeHead.slice(nonceLength) : null; completeHandshake.call(self, nonce, rest); } else { // nonce not present in upgradeHead, so we must wait for enough data // data to arrive before continuing var nonce = new Buffer(nonceLength); upgradeHead.copy(nonce, 0); var received = upgradeHead.length; var rest = null; var handler = function (data) { var toRead = Math.min(data.length, nonceLength - received); if (toRead === 0) return; data.copy(nonce, received, 0, toRead); received += toRead; if (received == nonceLength) { socket.removeListener('data', handler); if (toRead < data.length) rest = data.slice(toRead); completeHandshake.call(self, nonce, rest); } } socket.on('data', handler); } } // verify client var location = ((req.headers['x-forwarded-proto'] === 'https' || socket.encrypted) ? 'wss' : 'ws') + '://' + req.headers.host + req.url , origin = req.headers['origin']; if (typeof this.options.verifyClient == 'function') { var info = { origin: origin, secure: typeof req.connection.encrypted !== 'undefined', req: req }; if (this.options.verifyClient.length == 2) { var self = this; this.options.verifyClient(info, function(result) { if (!result) abortConnection(socket, 401, 'Unauthorized') else onClientVerified.apply(self); }); return; } else if (!this.options.verifyClient(info)) { abortConnection(socket, 401, 'Unauthorized'); return; } } onClientVerified(); } function abortConnection(socket, code, name) { try { var response = [ 'HTTP/1.1 ' + code + ' ' + name, 'Content-type: text/html' ]; socket.write(response.concat('', '').join('\r\n')); socket.end(); } catch (e) {} }
//// Protractor configuration file, see link for more information //// https://github.com/angular/protractor/blob/master/lib/config.ts //const { SpecReporter } = require('jasmine-spec-reporter'); //exports.config = { // allScriptsTimeout: 11000, // specs: [ // './e2e/**/*.e2e-spec.ts' // ], // capabilities: { // 'browserName': 'chrome' // }, // directConnect: true, // baseUrl: 'http://localhost:4200/', // framework: 'jasmine', // jasmineNodeOpts: { // showColors: true, // defaultTimeoutInterval: 30000, // print: function() {} // }, // onPrepare() { // require('ts-node').register({ // project: 'e2e/tsconfig.e2e.json' // }); // jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); // } //};
/* eslint-disable no-undef */ /* eslint-disable no-console */ let net = require('net'); let socks = require('./socks'); let server = net.createServer(); function info(tag, msg) { console.log(`${tag}:${JSON.stringify(msg)}`); } server.on('connection', client => { let state = 1; let remote1 = null; //let remote2 = null; let msg = null; //client.setTimeout(0); client.on('data', buffer => { switch (state) { case 1: msg = socks.versionMethod(buffer); info('received version method', msg); client.write(socks.versionMethodReply()); state = 2; break; case 2: msg = socks.requestDetail(buffer); info('received client request',msg); remote1 = net.createConnection(msg.DST_PORT,msg.DST_ADDR); remote1.on('connect',()=>{ console.log(`connect to ${msg.DST_ADDR}:${msg.DST_PORT} successfully`); console.log('proxy address:' + remote1.localAddress + ':' + remote1.localPort); let localAddress = remote1.localAddress.split('.').reduce((a,b)=>{ a.push(parseInt(b)); return a; },[]); let localPort = remote1.localPort; // let remoteAddress = remote1.remoteAddress.split('.').reduce((a,b)=>{ // a.push(parseInt(b)); // return a; // },[]); // let remotePort = remote1.remotePort; switch(msg.CMD){ case 1: //client.write(socks.replyRequest(0,1,localAddress,localPort)); client.write(socks.replyRequest(0,1,localAddress,localPort)); break; case 3: //connection.write(socks.replyRequest(0,msg.ATYP,remoteAddress,remotePort)); break; case 4: break; } state = 3; }); remote1.on('data',data=>{ //console.log('received:'+ data.byteLength); client.write(data); }); remote1.on('error',(error)=>{ client.end(); console.log(`connect to ${msg.DST_ADDR}:${msg.DST_PORT} failed. \n${error}`); }); remote1.on('end',()=>{ client.end(); console.log(`connect to ${msg.DST_ADDR}:${msg.DST_PORT} end.`); }); break; case 3: remote1.write(buffer); //console.log('sent:' + buffer.byteLength); break; } }); client.on('end', () => { remote1.end(); console.log('received FIN packet'); }); client.on('timeout',()=>{ console.log('client is timeout'); }); client.on('error',(error)=>{ remote1.end(); console.log('client error:'+ error); }); }); server.on('close',()=>{ console.log('server closed'); }); server.on('error', (error) => { console.log(error.stack); }); server.listen(parseInt(process.argv[2]), () => { console.log(`server started on ${server.address().port}`); });
import React, { Component } from "react"; import { Container, Row, Col, Button } from "reactstrap"; import "../App.css"; import { ReactComponent as Phone } from "../assets/svg/phone.svg"; import { ReactComponent as MapPin } from "../assets/svg/map-pin.svg"; import { ReactComponent as Mail } from "../assets/svg/mail.svg"; class Contact extends Component { render() { return ( <div className="subComponent-lg" id="contactBody"> <Container> <header className="headerTitle text-center"> <h1>Contact</h1> <p>GET IN TOUCH WITH US</p> </header> <section className="svg-group text-center"> <Row> {/* <Col lg="4" md="4"> <div className="svg-card-3"> <Phone width="50" height="55" strokeWidth="1" /> <p>0912 345 6789</p> </div> </Col> <Col lg="4" md="4"> <div className="svg-card-3"> <MapPin width="55" height="55" strokeWidth="1" /> <p>Manila City, Philippines</p> </div> </Col> */} <Col lg="4" md="4"> <div className="svg-card-3"> <Mail width="55" height="55" strokeWidth="1" /> <p>indiantourism@mgmail.com</p> </div> </Col> </Row> </section> <hr /> <br /> <section className="msg text-center"> <form action=""> <Row> <Col sm="6"> <input type="text" name="Name" id="reviewer-name" placeholder="Your Name" required /> <br /> <input type="email" name="Email" id="reviewer-email" placeholder="Your email" required /> </Col> <Col> <textarea name="Message" id="reviewer-message" rows="4" placeholder="Your Message" /> <Button outline color="light" className="float-left"> Send Message </Button> </Col> </Row> </form> </section> </Container> </div> ); } } export default Contact;
const { sum, sub, mult, div } = require("./operations"); const actionHandler = (operator, numbers) => { switch (operator) { case "sum": sum(numbers); break; case "sub": sub(numbers); break; case "mult": mult(numbers); break; case "div": div(numbers); break; default: console.log("unknown operation type"); } }; module.exports = actionHandler;
// Generated by purs bundle 0.14.4 var PS = {}; (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Control.Apply"] = $PS["Control.Apply"] || {}; var exports = $PS["Control.Apply"]; var apply = function (dict) { return dict.apply; }; exports["apply"] = apply; })(PS); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Control.Applicative"] = $PS["Control.Applicative"] || {}; var exports = $PS["Control.Applicative"]; var Control_Apply = $PS["Control.Apply"]; var pure = function (dict) { return dict.pure; }; var liftA1 = function (dictApplicative) { return function (f) { return function (a) { return Control_Apply.apply(dictApplicative.Apply0())(pure(dictApplicative)(f))(a); }; }; }; exports["pure"] = pure; exports["liftA1"] = liftA1; })(PS); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Control.Bind"] = $PS["Control.Bind"] || {}; var exports = $PS["Control.Bind"]; var bind = function (dict) { return dict.bind; }; var composeKleisli = function (dictBind) { return function (f) { return function (g) { return function (a) { return bind(dictBind)(f(a))(g); }; }; }; }; exports["bind"] = bind; exports["composeKleisli"] = composeKleisli; })(PS); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Control.Monad"] = $PS["Control.Monad"] || {}; var exports = $PS["Control.Monad"]; var Control_Applicative = $PS["Control.Applicative"]; var Control_Bind = $PS["Control.Bind"]; var ap = function (dictMonad) { return function (f) { return function (a) { return Control_Bind.bind(dictMonad.Bind1())(f)(function (f$prime) { return Control_Bind.bind(dictMonad.Bind1())(a)(function (a$prime) { return Control_Applicative.pure(dictMonad.Applicative0())(f$prime(a$prime)); }); }); }; }; }; exports["ap"] = ap; })(PS); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Data.Function"] = $PS["Data.Function"] || {}; var exports = $PS["Data.Function"]; var $$const = function (a) { return function (v) { return a; }; }; exports["const"] = $$const; })(PS); (function(exports) { "use strict"; exports.unit = {}; })(PS["Data.Unit"] = PS["Data.Unit"] || {}); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Data.Unit"] = $PS["Data.Unit"] || {}; var exports = $PS["Data.Unit"]; var $foreign = $PS["Data.Unit"]; exports["unit"] = $foreign.unit; })(PS); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Data.Functor"] = $PS["Data.Functor"] || {}; var exports = $PS["Data.Functor"]; var Data_Function = $PS["Data.Function"]; var Data_Unit = $PS["Data.Unit"]; var map = function (dict) { return dict.map; }; var $$void = function (dictFunctor) { return map(dictFunctor)(Data_Function["const"](Data_Unit.unit)); }; exports["void"] = $$void; })(PS); (function(exports) { "use strict"; exports.pureE = function (a) { return function () { return a; }; }; exports.bindE = function (a) { return function (f) { return function () { return f(a())(); }; }; }; })(PS["Effect"] = PS["Effect"] || {}); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Effect"] = $PS["Effect"] || {}; var exports = $PS["Effect"]; var $foreign = $PS["Effect"]; var Control_Applicative = $PS["Control.Applicative"]; var Control_Monad = $PS["Control.Monad"]; var monadEffect = { Applicative0: function () { return applicativeEffect; }, Bind1: function () { return bindEffect; } }; var bindEffect = { bind: $foreign.bindE, Apply0: function () { return applyEffect; } }; var applyEffect = { apply: Control_Monad.ap(monadEffect), Functor0: function () { return functorEffect; } }; var applicativeEffect = { pure: $foreign.pureE, Apply0: function () { return applyEffect; } }; var functorEffect = { map: Control_Applicative.liftA1(applicativeEffect) }; exports["functorEffect"] = functorEffect; exports["applicativeEffect"] = applicativeEffect; exports["bindEffect"] = bindEffect; })(PS); (function(exports) { "use strict"; exports.runEffectFn1 = function runEffectFn1(fn) { return function(a) { return function() { return fn(a); }; }; }; exports.runEffectFn2 = function runEffectFn2(fn) { return function(a) { return function(b) { return function() { return fn(a, b); }; }; }; }; exports.runEffectFn3 = function runEffectFn3(fn) { return function(a) { return function(b) { return function(c) { return function() { return fn(a, b, c); }; }; }; }; }; })(PS["Effect.Uncurried"] = PS["Effect.Uncurried"] || {}); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Effect.Uncurried"] = $PS["Effect.Uncurried"] || {}; var exports = $PS["Effect.Uncurried"]; var $foreign = $PS["Effect.Uncurried"]; exports["runEffectFn1"] = $foreign.runEffectFn1; exports["runEffectFn2"] = $foreign.runEffectFn2; exports["runEffectFn3"] = $foreign.runEffectFn3; })(PS); (function(exports) { "use strict"; function create() { return new Phaser.Game(); } exports.create = create; exports.setGameDimensionsImpl = function ({ width, height }, game) { game.config.width = width; game.config.height = height; return game; }; })(PS["Graphics.Phaser"] = PS["Graphics.Phaser"] || {}); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Graphics.Phaser"] = $PS["Graphics.Phaser"] || {}; var exports = $PS["Graphics.Phaser"]; var $foreign = $PS["Graphics.Phaser"]; var Effect_Uncurried = $PS["Effect.Uncurried"]; var setGameDimensions = Effect_Uncurried.runEffectFn2($foreign.setGameDimensionsImpl); exports["setGameDimensions"] = setGameDimensions; exports["create"] = $foreign.create; })(PS); (function(exports) { 'use strict'; // https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Graphics.html exports.createImpl = function (scene) { return scene.add.graphics(); }; exports.fillStyleImpl = function (color, alpha, graphic) { graphic.fillStyle(color, alpha); return graphic; }; exports.fillRectImpl = function ({ x, y }, { width, height }, graphic) { graphic.fillRect(x, y, width, height); return graphic; }; })(PS["Graphics.Phaser.Graphics"] = PS["Graphics.Phaser.Graphics"] || {}); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Graphics.Phaser.Graphics"] = $PS["Graphics.Phaser.Graphics"] || {}; var exports = $PS["Graphics.Phaser.Graphics"]; var $foreign = $PS["Graphics.Phaser.Graphics"]; var Effect_Uncurried = $PS["Effect.Uncurried"]; var fillStyle = Effect_Uncurried.runEffectFn3($foreign.fillStyleImpl); var fillRect = Effect_Uncurried.runEffectFn3($foreign.fillRectImpl); var create = Effect_Uncurried.runEffectFn1($foreign.createImpl); exports["create"] = create; exports["fillStyle"] = fillStyle; exports["fillRect"] = fillRect; })(PS); (function(exports) { "use strict"; exports.addSceneImpl = function ( { key, init, create, update, preload, autoStart }, game ) { const config = { init: function () { init(this)(); }, preload: function () { preload(this)(); }, create: function () { create(this)(); }, update: function () { update(this)(); }, }; game.scene.add(key, config, autoStart); return game; }; })(PS["Graphics.Phaser.Scene"] = PS["Graphics.Phaser.Scene"] || {}); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Graphics.Phaser.Scene"] = $PS["Graphics.Phaser.Scene"] || {}; var exports = $PS["Graphics.Phaser.Scene"]; var $foreign = $PS["Graphics.Phaser.Scene"]; var Control_Applicative = $PS["Control.Applicative"]; var Data_Unit = $PS["Data.Unit"]; var Effect = $PS["Effect"]; var Effect_Uncurried = $PS["Effect.Uncurried"]; var defaultSceneConfig = { key: "", autoStart: false, create: function (_scene) { return Control_Applicative.pure(Effect.applicativeEffect)(Data_Unit.unit); }, init: function (_scene) { return Control_Applicative.pure(Effect.applicativeEffect)(Data_Unit.unit); }, update: function (_scene) { return Control_Applicative.pure(Effect.applicativeEffect)(Data_Unit.unit); }, preload: function (_scene) { return Control_Applicative.pure(Effect.applicativeEffect)(Data_Unit.unit); } }; var addScene = Effect_Uncurried.runEffectFn2($foreign.addSceneImpl); exports["defaultSceneConfig"] = defaultSceneConfig; exports["addScene"] = addScene; })(PS); (function($PS) { // Generated by purs version 0.14.4 "use strict"; $PS["Main"] = $PS["Main"] || {}; var exports = $PS["Main"]; var Control_Bind = $PS["Control.Bind"]; var Data_Functor = $PS["Data.Functor"]; var Effect = $PS["Effect"]; var Graphics_Phaser = $PS["Graphics.Phaser"]; var Graphics_Phaser_Graphics = $PS["Graphics.Phaser.Graphics"]; var Graphics_Phaser_Scene = $PS["Graphics.Phaser.Scene"]; var drawRedRect = Control_Bind.composeKleisli(Effect.bindEffect)(Graphics_Phaser_Graphics.fillStyle("0xff0000")(0.5))(Graphics_Phaser_Graphics.fillRect({ x: 250.0, y: 200.0 })({ width: 400.0, height: 256.0 })); var drawGreenRect = Control_Bind.composeKleisli(Effect.bindEffect)(Graphics_Phaser_Graphics.fillStyle("0x00ff00")(1.0))(Graphics_Phaser_Graphics.fillRect({ x: 100.0, y: 100.0 })({ width: 256.0, height: 256.0 })); var create = function (scene) { return Data_Functor["void"](Effect.functorEffect)(Control_Bind.bind(Effect.bindEffect)(Control_Bind.bind(Effect.bindEffect)(Graphics_Phaser_Graphics.create(scene))(drawGreenRect))(drawRedRect)); }; var mainScene = { key: Graphics_Phaser_Scene.defaultSceneConfig.key, autoStart: true, create: create, init: Graphics_Phaser_Scene.defaultSceneConfig.init, update: Graphics_Phaser_Scene.defaultSceneConfig.update, preload: Graphics_Phaser_Scene.defaultSceneConfig.preload }; var main = Control_Bind.bind(Effect.bindEffect)(Control_Bind.bind(Effect.bindEffect)(Graphics_Phaser.create)(Graphics_Phaser.setGameDimensions({ width: 800.0, height: 600.0 })))(Graphics_Phaser_Scene.addScene(mainScene)); exports["main"] = main; exports["drawGreenRect"] = drawGreenRect; exports["drawRedRect"] = drawRedRect; exports["create"] = create; exports["mainScene"] = mainScene; })(PS); PS["Main"].main();
const path = require('path') const express = require('express') const morgan = require('morgan') const compression = require('compression') const session = require('express-session') const passport = require('passport') const SequelizeStore = require('connect-session-sequelize')(session.Store) const db = require('./db') const sessionStore = new SequelizeStore({db}) const PORT = process.env.PORT || 8080 const app = express() const socketio = require('socket.io') const {RTMClient, WebClient} = require('@slack/client') var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3') const axios = require('axios') module.exports = app // This is a global Mocha hook, used for resource cleanup. // Otherwise, Mocha v4+ never quits after tests. if (process.env.NODE_ENV === 'test') { after('close the session store', () => sessionStore.stopExpiringSessions()) } /** * In your development environment, you can keep all of your * app's secret API keys in a file called `secrets.js`, in your project * root. This file is included in the .gitignore - it will NOT be tracked * or show up on Github. On your production server, you can add these * keys as environment variables, so that they can still be read by the * Node process on process.env */ if (process.env.NODE_ENV !== 'production') require('../secrets') // passport registration passport.serializeUser((user, done) => done(null, user.id)) passport.deserializeUser(async (id, done) => { try { const user = await db.models.user.findById(id) done(null, user) } catch (err) { done(err) } }) const createApp = () => { const channels = {} const sendFunny = async (rtm, message) => { const memeList = [] const results = await axios.get( 'https://www.reddit.com/r/wholesomememes/top.json?limit=100' ) results.data.data.children.forEach(post => { if (post.data.url.endsWith('gifv')) { memeList.push(post.data.url) } if (post.data.url.endsWith('gif')) { memeList.push(post.data.url) } if (post.data.url.endsWith('jpg')) { memeList.push(post.data.url) } if (post.data.url.endsWith('png')) { memeList.push(post.data.url) } }) const meme = memeList[Math.floor(Math.random() * memeList.length)] rtm.sendMessage(meme, message.channel) } var toneAnalyzer = new ToneAnalyzerV3({ iam_apikey: process.env.WATSON_API_KEY, version: '2017-09-21', url: 'https://gateway.watsonplatform.net/tone-analyzer/api/' }) const token = process.env.SLACK_BOT_TOKEN const rtm = new RTMClient(token) rtm.start() const web = new WebClient(token) rtm.on('message', event => { const message = event if ( (message.subtype && message.subtype === 'bot_message') || (!message.subtype && message.user === rtm.activeUserId) ) { return } if (!channels[message.channel]) { channels[message.channel] = 0 } let currentMood = channels[message.channel] toneAnalyzer.tone( { tone_input: message.text, content_type: 'text/plain' }, function(err, tone) { if (err) { console.log(err) } else { tone.document_tone.tones.forEach(emote => { if (emote.tone_id === 'joy') { currentMood = currentMood + emote.score * 10 } if (emote.tone_id === 'sadness') { currentMood = currentMood - emote.score * 10 } if (emote.tone_id === 'anger') { currentMood = currentMood - emote.score * 10 } if (emote.tone_id === 'fear') { currentMood = currentMood - emote.score * 10 } }) if (currentMood <= -30) { sendFunny(rtm, message) currentMood = 0 } if (currentMood >= 100) { rtm.sendMessage( 'This is such a positive environment! Keep up the good work everyone!', message.channel ) currentMood = 20 } channels[message.channel] = currentMood console.log('tone endpoint:') console.log(JSON.stringify(tone.document_tone.tones, null, 2)) console.log('current mood:', currentMood) } } ) }) app.get('/channels', (req, res, next) => { // console.log(channels) res.json(channels) }) // logging middleware app.use(morgan('dev')) // body parsing middleware app.use(express.json()) app.use(express.urlencoded({extended: true})) // compression middleware app.use(compression()) // session middleware with passport app.use( session({ secret: process.env.SESSION_SECRET || 'my best friend is Cody', store: sessionStore, resave: false, saveUninitialized: false }) ) app.use(passport.initialize()) app.use(passport.session()) // auth and api routes app.use('/auth', require('./auth')) app.use('/api', require('./api')) // static file-serving middleware app.use(express.static(path.join(__dirname, '..', 'public'))) // any remaining requests with an extension (.js, .css, etc.) send 404 app.use((req, res, next) => { if (path.extname(req.path).length) { const err = new Error('Not found') err.status = 404 next(err) } else { next() } }) // sends index.html app.use('*', (req, res) => { res.sendFile(path.join(__dirname, '..', 'public/index.html')) }) // error handling endware app.use((err, req, res, next) => { console.error(err) console.error(err.stack) res.status(err.status || 500).send(err.message || 'Internal server error.') }) } const startListening = () => { // start listening (and create a 'server' object representing our server) const server = app.listen(PORT, () => console.log(`Mixing it up on port ${PORT}`) ) // set up our socket control center const io = socketio(server) require('./socket')(io) } const syncDb = () => db.sync() async function bootApp() { await sessionStore.sync() await syncDb() await createApp() await startListening() } // This evaluates as true when this file is run directly from the command line, // i.e. when we say 'node server/index.js' (or 'nodemon server/index.js', or 'nodemon server', etc) // It will evaluate false when this module is required by another module - for example, // if we wanted to require our app in a test spec if (require.main === module) { bootApp() } else { createApp() }
import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk'; import Router from './components/Router' import rootReducer from './store/reducers/rootReducer' import './css/index.css'; const store = createStore(rootReducer, applyMiddleware(thunk)); const App = () => { return( <Router /> ) } ReactDOM.render(<Provider store={store}><App /></Provider>, document.querySelector('#root'))
/** * WordPress View plugin. */ (function() { var VK = tinymce.VK, TreeWalker = tinymce.dom.TreeWalker, selected; tinymce.create('tinymce.plugins.wpView', { init : function( editor, url ) { var wpView = this; // Check if the `wp.mce` API exists. if ( typeof wp === 'undefined' || ! wp.mce ) return; editor.onPreInit.add( function( editor ) { // Add elements so we can set `contenteditable` to false. editor.schema.addValidElements('div[*],span[*]'); }); // When the editor's content changes, scan the new content for // matching view patterns, and transform the matches into // view wrappers. Since the editor's DOM is outdated at this point, // we'll wait to render the views. editor.onBeforeSetContent.add( function( editor, o ) { if ( ! o.content ) return; o.content = wp.mce.view.toViews( o.content ); }); // When the editor's content has been updated and the DOM has been // processed, render the views in the document. editor.onSetContent.add( function( editor, o ) { wp.mce.view.render( editor.getDoc() ); }); editor.onInit.add( function( editor ) { // When a view is selected, ensure content that is being pasted // or inserted is added to a text node (instead of the view). editor.selection.onBeforeSetContent.add( function( selection, o ) { var view = wpView.getParentView( selection.getNode() ), walker, target; // If the selection is not within a view, bail. if ( ! view ) return; // If there are no additional nodes or the next node is a // view, create a text node after the current view. if ( ! view.nextSibling || wpView.isView( view.nextSibling ) ) { target = editor.getDoc().createTextNode(''); editor.dom.insertAfter( target, view ); // Otherwise, find the next text node. } else { walker = new TreeWalker( view.nextSibling, view.nextSibling ); target = walker.next(); } // Select the `target` text node. selection.select( target ); selection.collapse( true ); }); // When the selection's content changes, scan any new content // for matching views and immediately render them. // // Runs on paste and on inserting nodes/html. editor.selection.onSetContent.add( function( selection, o ) { if ( ! o.context ) return; var node = selection.getNode(); if ( ! node.innerHTML ) return; node.innerHTML = wp.mce.view.toViews( node.innerHTML ); wp.mce.view.render( node ); }); }); // When the editor's contents are being accessed as a string, // transform any views back to their text representations. editor.onPostProcess.add( function( editor, o ) { if ( ( ! o.get && ! o.save ) || ! o.content ) return; o.content = wp.mce.view.toText( o.content ); }); // Triggers when the selection is changed. // Add the event handler to the top of the stack. editor.onNodeChange.addToTop( function( editor, controlManager, node, collapsed, o ) { var view = wpView.getParentView( node ); // Update the selected view. if ( view ) { wpView.select( view ); // Prevent the selection from propagating to other plugins. return false; // If we've clicked off of the selected view, deselect it. } else { wpView.deselect(); } }); editor.onKeyDown.addToTop( function( editor, event ) { var keyCode = event.keyCode, view, instance; // If a view isn't selected, let the event go on its merry way. if ( ! selected ) return; // If the caret is not within the selected view, deselect the // view and bail. view = wpView.getParentView( editor.selection.getNode() ); if ( view !== selected ) { wpView.deselect(); return; } // If delete or backspace is pressed, delete the view. if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) { if ( (instance = wp.mce.view.instance( selected )) ) { instance.remove(); wpView.deselect(); } } // Let keypresses that involve the command or control keys through. // Also, let any of the F# keys through. if ( event.metaKey || event.ctrlKey || ( keyCode >= 112 && keyCode <= 123 ) ) return; event.preventDefault(); }); }, getParentView : function( node ) { while ( node ) { if ( this.isView( node ) ) return node; node = node.parentNode; } }, isView : function( node ) { return (/(?:^|\s)wp-view-wrap(?:\s|$)/).test( node.className ); }, select : function( view ) { if ( view === selected ) return; this.deselect(); selected = view; wp.mce.view.select( selected ); }, deselect : function() { if ( selected ) wp.mce.view.deselect( selected ); selected = null; }, getInfo : function() { return { longname : 'WordPress Views', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '1.0' }; } }); // Register plugin tinymce.PluginManager.add( 'wpview', tinymce.plugins.wpView ); })();
document.querySelectorAll('.sidebar-submenu').forEach(e => { e.querySelector('.sidebar-menu-dropdown').onclick = (event) => { event.preventDefault() e.querySelector('.sidebar-menu-dropdown .dropdown-icon').classList.toggle('active') let dropdown_content = e.querySelector('.sidebar-menu-dropdown-content') let dropdown_content_lis = dropdown_content.querySelectorAll('li') let active_height = dropdown_content_lis[0].clientHeight * dropdown_content_lis.length dropdown_content.classList.toggle('active') dropdown_content.style.height = dropdown_content.classList.contains('active') ? active_height + 'px' : '0' } }) let category_options = { series: [44, 55, 41, 17], labels: ['Maths', 'English', 'History', 'Geography'], chart: { type: 'donut', }, colors: ['#6ab04c', '#2980b9', '#f39c12', '#d35400'] } let category_chart = new ApexCharts(document.querySelector("#category-chart"), category_options) category_chart.render() let customer_options = { series: [{ name: "Basic skills", data: [40, 70, 20, 90, 36, 80, 30, 91, 60] },{ name: "Advanced skills", data: [20, 30, 10, 20, 16, 40, 20, 51, 10] }], colors: ['#6ab04c', '#2980b9'], chart: { height: 350, type: 'line', }, dataLabels: { enabled: false }, stroke: { curve: 'smooth' }, xaxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'], }, legend: { position: 'top' } } let customer_chart = new ApexCharts(document.querySelector("#customer-chart"), customer_options) customer_chart.render() setDarkChart = (dark) => { let theme = { theme: { mode: dark ? 'dark' : 'light' } } customer_chart.updateOptions(theme) category_chart.updateOptions(theme) } // DARK MODE TOGGLE let darkmode_toggle = document.querySelector('#darkmode-toggle') darkmode_toggle.onclick = (e) => { e.preventDefault() document.querySelector('body').classList.toggle('dark') darkmode_toggle.querySelector('.darkmode-switch').classList.toggle('active') setDarkChart(document.querySelector('body').classList.contains('dark')) } let overlay = document.querySelector('.overlay') let sidebar = document.querySelector('.sidebar') document.querySelector('#mobile-toggle').onclick = () => { sidebar.classList.toggle('active') overlay.classList.toggle('active') } document.querySelector('#sidebar-close').onclick = () => { sidebar.classList.toggle('active') overlay.classList.toggle('active') }
// @flow import optionalRequire from '../Utils/OptionalRequire.js'; import { type ExternalEditorOpenOptions } from './ResourceExternalEditor.flow'; import { createOrUpdateResource, getLocalResourceFullPath, } from './ResourceUtils.js'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); const ipcRenderer = electron ? electron.ipcRenderer : null; const gd = global.gd; /** * Open JFXR to create wav resources. */ export const openJfxr = ({ project, resourcesLoader, resourceNames, onChangesSaved, resourcePath, extraOptions, }: ExternalEditorOpenOptions) => { if (!electron || !ipcRenderer) return; const projectPath = path.dirname(project.getProjectFile()); const initialResourcePath = getLocalResourceFullPath( project, resourceNames[0] ); const externalEditorData = { resourcePath: initialResourcePath, externalEditorData: extraOptions.externalEditorData, projectPath, }; ipcRenderer.removeAllListeners('jfxr-changes-saved'); ipcRenderer.on( 'jfxr-changes-saved', (event, newFilePath, externalEditorData) => { const name = path.relative(projectPath, newFilePath); createOrUpdateResource(project, new gd.AudioResource(), name); const metadata = { jfxr: externalEditorData, }; project .getResourcesManager() .getResource(name) .setMetadata(JSON.stringify(metadata)); onChangesSaved([{ metadata, name }]); } ); ipcRenderer.send('jfxr-create-wav', externalEditorData); };
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-55198bd8"],{"38d7":function(t,e,n){},4873:function(t,e,n){"use strict";var s=n("38d7"),i=n.n(s);i.a},"679b":function(t,e,n){},"7c58":function(t,e,n){"use strict";n.r(e);var s=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{ref:"recommend",staticClass:"recommend"},[n("cube-scroll",{ref:"scroll",staticClass:"recommend-content",attrs:{data:t.songLists}},[n("div",{staticClass:"slider-item"}),n("slider",{staticClass:"slider-self"}),n("div",{staticClass:"recommend-list-header"},[t._v("推荐歌单")]),n("ul",{staticClass:"songlist-ul"},t._l(t.songLists,(function(e,s){return n("li",{key:s,staticClass:"songList-item",on:{click:function(n){return t.selectItem(e)}}},[n("img",{directives:[{name:"lazy",rawName:"v-lazy",value:e.picUrl,expression:"songlist.picUrl"}]}),n("div",{staticClass:"song-info"},[t._v(t._s(e.name))]),n("div",{staticClass:"playCount-container"},[n("svg",{staticClass:"icon",attrs:{"aria-hidden":"true"}},[n("use",{staticStyle:{"font-size":"12px"},attrs:{"xlink:href":"#icon-cloud-headset"}})]),t._v("\n "+t._s(t.playCountNum(e))+"\n ")])])})),0),n("cube-loading",{directives:[{name:"show",rawName:"v-show",value:!t.songLists.length,expression:"!songLists.length"}],staticClass:"loading_container",attrs:{size:40}}),n("div",{staticClass:"recommend-list-header"},[t._v("推荐歌曲")]),n("ul",{staticClass:"songlist-ul"},t._l(t.newSongs,(function(e,s){return n("li",{key:s,staticClass:"songList-item",on:{click:function(n){return t.selectItem(e)}}},[n("img",{directives:[{name:"lazy",rawName:"v-lazy",value:e.song.album.blurPicUrl,expression:"songlist.song.album.blurPicUrl"}]}),n("div",{staticClass:"newsong-info"},[t._v(t._s(e.name))]),n("div",{staticClass:"song-author"},[t._v(t._s(e.song.artists[0].name))])])})),0),n("cube-loading",{directives:[{name:"show",rawName:"v-show",value:!t.newSongs.length,expression:"!newSongs.length"}],staticClass:"loading_container",attrs:{size:40}})],1),n("router-view")],1)},i=[],r=(n("5ab2"),n("6d57"),n("e10e"),n("2b45"),n("ce3c")),a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("cube-slide",{ref:"slide",staticClass:"slider",attrs:{data:t.bannerList},scopedSlots:t._u([{key:"dots",fn:function(e){return t._l(e.dots,(function(s,i){return n("span",{key:i,staticClass:"slide-dot",class:{active:e.current===i}},[t._v(t._s(i+1))])}))}}])},t._l(t.bannerList,(function(t,e){return n("cube-slide-item",{key:e,staticClass:"slider-group"},[n("img",{staticClass:"slider-item",attrs:{src:t.imageUrl}})])})),1)},c=[],o=n("f753"),l=n.n(o),u=n("41ea");function d(){return l.a.get("".concat(u["b"],"/banner")).then((function(t){return t.data}))}function f(){return l.a.get("".concat(u["b"],"/personalized"))}function g(){return l.a.get("".concat(u["b"],"/personalized/newsong"))}var m={data:function(){return{bannerList:[]}},mounted:function(){this._getBannerList()},methods:{_getBannerList:function(){var t=this;d().then((function(e){t.bannerList=e.banners})).catch((function(t){console.log(t)}))}}},v=m,h=(n("c6c1"),n("9ca4")),b=Object(h["a"])(v,a,c,!1,null,"2715fb17",null),p=b.exports,w=n("510f"),y=n("9f3a");function C(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,s)}return n}function _(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?C(Object(n),!0).forEach((function(e){Object(r["a"])(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):C(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}var O={mixins:[w["b"]],components:{Slider:p},data:function(){return{songLists:[],newSongs:[]}},mounted:function(){var t=this;setTimeout((function(){t.getSonglist(),t.getNewSong()}),1e3)},methods:_({selectItem:function(t){this.$router.push({path:"/recommend/".concat(t.id)}),this.setDisc(t)},handlePlaylist:function(t){var e=t.length>0?"60px":0;this.$refs.recommend.style.bottom=e,this.$refs.scroll.refresh()},getSonglist:function(){var t=this;f().then((function(e){t.songLists=e.data.result}))},getNewSong:function(){var t=this;g().then((function(e){for(var n=0;n<9;n++)t.newSongs.push(e.data.result[n])}))},playCountNum:function(t){var e=Math.ceil(t.playCount).toString();if(e.length>9){var n=e.slice(-10,-9);return n+"亿"}if(e.length>5){var s=e.slice(0,-4);return s+"万"}return e}},Object(y["d"])({setDisc:"SET_DISC"}))},S=O,j=(n("4873"),Object(h["a"])(S,s,i,!1,null,"73d8ad69",null));e["default"]=j.exports},c6c1:function(t,e,n){"use strict";var s=n("679b"),i=n.n(s);i.a}}]); //# sourceMappingURL=chunk-55198bd8.fe9596b2.js.map
//// [assignFromNumberInterface.js] var x = 1; var a; x = a; a = x;
const { declare } = require('@babel/helper-plugin-utils'); module.exports = declare(() => ({ manipulateOptions({ parserOpts }) { parserOpts.plugins.push(['decorators-legacy']); }, }));
(function ($, undefined) { /* Filter menu operator messages */ if (kendo.ui.FilterCell) { kendo.ui.FilterCell.prototype.options.operators = $.extend(true, kendo.ui.FilterCell.prototype.options.operators,{ "date": { "eq": "Eşittir", "gt": "Sonra", "gte": "Sonra ya da eşit", "lt": "Önce", "lte": "Önce ya da eşit", "neq": "Eşit değildir" }, "enums": { "eq": "Eşittir", "neq": "Eşit değildir" }, "number": { "eq": "Eşittir", "gt": "Büyüktür", "gte": "Daha büyük veya eşittir", "lt": "Daha küçük", "lte": "Daha küçük veya eşit", "neq": "Eşit değildir" }, "string": { "contains": "İçeriyor", "doesnotcontain": "İçermiyor", "endswith": "İle biter", "eq": "Eşittir", "neq": "Eşit değildir", "startswith": "İle başlar" } }); } /* Filter menu operator messages */ if (kendo.ui.FilterMenu) { kendo.ui.FilterMenu.prototype.options.operators = $.extend(true, kendo.ui.FilterMenu.prototype.options.operators,{ "date": { "eq": "Eşittir", "gt": "Sonra", "gte": "Sonra ya da eşit", "lt": "Önce", "lte": "Önce ya da eşit", "neq": "Eşit değildir" }, "enums": { "eq": "Eşittir", "neq": "Eşit değildir" }, "number": { "eq": "Eşittir", "gt": "Büyüktür", "gte": "Daha büyük veya eşittir", "lt": "Daha küçük", "lte": "Daha küçük veya eşit", "neq": "Eşit değildir" }, "string": { "contains": "İçeriyor", "doesnotcontain": "İçermiyor", "endswith": "İle biter", "eq": "Eşittir", "neq": "Eşit değildir", "startswith": "İle başlar" } }); } /* ColumnMenu messages */ if (kendo.ui.ColumnMenu) { kendo.ui.ColumnMenu.prototype.options.messages = $.extend(true, kendo.ui.ColumnMenu.prototype.options.messages,{ "columns": "Sütunlar", "settings": "Sütun ayarları", "done": "Tamam", "lock": "Kilitle", "sortAscending": "Artan Sıralama", "sortDescending": "Azalan Sıralama", "unlock": "Kilidini Aç" }); } /* RecurrenceEditor messages */ if (kendo.ui.RecurrenceEditor) { kendo.ui.RecurrenceEditor.prototype.options.messages = $.extend(true, kendo.ui.RecurrenceEditor.prototype.options.messages,{ "daily": { "interval": "Günler", "repeatEvery": "Her gün tekrarla" }, "end": { "after": "Sonra", "label": "Bitiş", "mobileLabel": "Bitiş", "never": "Asla/Hiç", "occurrence": "Olay", "on": "Anlık" }, "frequencies": { "daily": "Günlük", "monthly": "Aylık", "never": "Asla/Hiç", "weekly": "Haftalık", "yearly": "Yıllık" }, "monthly": { "day": "Gün", "interval": "Aylar", "repeatEvery": "Her ay tekrarla", "repeatOn": "Tekrarla" }, "offsetPositions": { "first": "İlk", "fourth": "Dördüncü", "last": "Son", "second": "İkinci", "third": "Üçüncü" }, "weekdays": { "day": "Gün", "weekday": "İş günü", "weekend": "Haftasonu" }, "weekly": { "interval": "Haftalar", "repeatEvery": "Her hafta tekrarla", "repeatOn": "Tekrarla" }, "yearly": { "interval": "Yıllar", "of": "Arasında", "repeatEvery": "Her Yıl Tekrarla", "repeatOn": "Tekrarla" } }); } /* Editor messages */ if (kendo.ui.Editor) { kendo.ui.Editor.prototype.options.messages = $.extend(true, kendo.ui.Editor.prototype.options.messages,{ "addColumnLeft": "Sola kolon ekle", "addColumnRight": "Sağa kolon ekle", "addRowAbove": "Yukarıdaki satır ekle", "addRowBelow": "Aşağıdaki satır ekle", "backColor": "Arka plan rengi", "bold": "Kalın ", "createLink": "Köprü ekleme", "createTable": "Tablo oluştur", "deleteColumn": "Sütun silme", "deleteFile": "Silmek istediğinizden emin misiniz ?", "deleteRow": "Satır sil", "dialogButtonSeparator": "ya da", "dialogCancel": "İptal", "dialogInsert": "Ekle", "dialogUpdate": "Güncelle", "directoryNotFound": "Bu isimde bir dizin bulunamadı.", "dropFilesHere": "Yüklemek için dosyaları buraya bırakın", "emptyFolder": "Boş klasör", "fontName": "Font ailesi Seçiniz", "fontNameInherit": "Devralınan Karakter", "fontSize": "Font boyutu Seçiniz", "fontSizeInherit": "Devralınan Boyut", "foreColor": "Renk", "formatBlock": "Biçim", "formatting": "Biçimlendirme", "imageAltText": "Alternatif metin", "imageWebAddress": "Web adresi", "indent": "Aatırbaşı", "insertHtml": "HTML ekle", "insertImage": "Resim ekle", "insertOrderedList": "Sıralı liste ekleme", "insertUnorderedList": "Sırasız liste ekleme", "invalidFileType": "Seçinizilen dosya \"{0}\" geçerli değil. Desteklenen dosya türleri {1} vardır.", "italic": "İtalik karakter", "justifyCenter": "Merkezi metin", "justifyFull": "Doğrulama", "justifyLeft": "Metni sola yasla", "justifyRight": "Metni sağa yasla", "linkOpenInNewWindow": "Yeni pencerede aç", "linkText": "Metin", "linkToolTip": "Araç İpucu", "linkWebAddress": "Web address", "orderBy": "Düzenleme ölçütü:", "orderByName": "İsim", "orderBySize": "Boyut", "outdent": "Çıkıntı", "overwriteFile": "İsimde bir dosya \"{0}\" zaten dizinde mevcut. Bunu üzerine yazmak istiyor musunuz?", "search": "Arama", "strikethrough": "Üstü çizili", "styles": "Stiller", "subscript": "İndis", "superscript": "Üstyazı", "underline": "Altını çizmek", "unlink": "Köprüyü Kaldır", "uploadFile": "Yükle", "viewHtml": "HTML Görünümü ", "insertFile": "Insert file" }); } /* FilterCell messages */ if (kendo.ui.FilterCell) { kendo.ui.FilterCell.prototype.options.messages = $.extend(true, kendo.ui.FilterCell.prototype.options.messages,{ "clear": "Temizle", "filter": "Filtre", "isFalse": "FALSE", "isTrue": "Doğru ", "operator": "Operatör(işletmen)" }); } /* FilterMenu messages */ if (kendo.ui.FilterMenu) { kendo.ui.FilterMenu.prototype.options.messages = $.extend(true, kendo.ui.FilterMenu.prototype.options.messages,{ "and": "Ve", "cancel": "İptal", "clear": "Temizle", "filter": "Filtre", "info": "bu ile bu arasındaki değerleri göster", "isFalse": "FALSE", "isTrue": "Doğru ", "operator": "Operatör(işletmen)", "or": "ya da", "selectValue": "Değer Seçiniziniz", "value": "Değer" }); } /* Grid messages */ if (kendo.ui.Grid) { kendo.ui.Grid.prototype.options.messages = $.extend(true, kendo.ui.Grid.prototype.options.messages,{ "commands": { "canceledit": "İptal", "cancel": "Değişiklikleri iptal et", "create": "Yeni Kayıt Ekle", "destroy": "Sil", "edit": "Düzenle", "excel": "Export to Excel", "pdf": "Export to PDF", "save": "Değişiklikleri Kaydet", "select": "Seçiniz", "update": "Güncelle" }, "editable": { "cancelDelete": "İptal", "confirmation": "Kayıtları Silmek istediğinizden emin misiniz ?", "confirmDelete": "Sil" } }); } /* Groupable messages */ if (kendo.ui.Groupable) { kendo.ui.Groupable.prototype.options.messages = $.extend(true, kendo.ui.Groupable.prototype.options.messages,{ "empty": "Bir sütun başlığını sürükleyin ve bu sütuna göre gruplandırmak için buraya bırakın" }); } /* Pager messages */ if (kendo.ui.Pager) { kendo.ui.Pager.prototype.options.messages = $.extend(true, kendo.ui.Pager.prototype.options.messages,{ "display": "{0} - {1} aralığı gösteriliyor. Toplam {2} öğe var", "empty": "Görüntülenecek öğe yok", "first": "İlk sayfaya git", "itemsPerPage": "Sayfa başına ürün", "last": "Son sayfaya git", "morePages": "Daha fazla sayfa", "next": "Bir sonraki sayfaya git", "of": "{0}", "page": "Sayfa", "previous": "Sayfaları İncele", "refresh": "Güncelle" }); } /* Scheduler messages */ if (kendo.ui.Scheduler) { kendo.ui.Scheduler.prototype.options.messages = $.extend(true, kendo.ui.Scheduler.prototype.options.messages,{ "allDay": "Tüm gün", "cancel": "İptal Et", "editable": { "confirmation": "Bu etkinliği silmek istediğinizden emin misiniz?" }, "date": "Tarih", "deleteWindowTitle": "Etkinliği sil", "destroy": "Sil", "editor": { "allDayEvent": "Tüm gün süren olay", "description": "Tanım", "editorTitle": "Olay", "end": "Bitiş", "endTimezone": "Bitiş saati", "noTimezone": "Zaman Aralığı belirtilmemiş", "repeat": "Tekrar", "separateTimezones": "Ayrı bir başlangıç ve bitiş Zaman aralığı kullan", "start": "Başlangıç", "startTimezone": "Başlangıç Saati", "timezone": "", "timezoneEditorButton": "Zaman Aralığı", "timezoneEditorTitle": "Zaman Aralığı", "title": "Tanım" }, "event": "Olay", "recurrenceMessages": { "deleteRecurring": "Sadece bu olayı ya da bütün dizini mi silmek istiyor musunuz?", "deleteWindowOccurrence": "Geçerli yinelemeyi Sil", "deleteWindowSeries": "Seriyi Sil", "deleteWindowTitle": "Tekrarlanan Öğeyi Sil", "editRecurring": "Sadece bu olay oluşumunu veya tüm dizini düzenlemek istiyor musunuz?", "editWindowOccurrence": "Geçerli Olayı Düzenle", "editWindowSeries": "Seriyi düzenle", "editWindowTitle": "Tekrarlanan Öğeyi Düzenle" }, "save": "Kaydet", "showFullDay": "Tüm gün göster", "showWorkDay": "İş saatlerini göster", "time": "Zaman", "today": "Bugün", "views": { "agenda": "Gündem", "day": "Gün", "month": "Ay", "week": "Hafta", "workWeek": "Çalışma Haftası" } }); } /* Upload messages */ if (kendo.ui.Upload) { kendo.ui.Upload.prototype.options.localization = $.extend(true, kendo.ui.Upload.prototype.options.localization,{ "cancel": "İptal Et", "dropFilesHere": "Yüklemek için dosyaları buraya bırakın", "headerStatusUploaded": "Tamalandı", "headerStatusUploading": "Yükleniyor", "remove": "Kaldır", "retry": "Tekrar Dene", "select": "Seçiniz", "statusFailed": "Başarız Oldu", "statusUploaded": "Yüklendi", "statusUploading": "Yükleniyor", "uploadSelectedFiles": "seçilen dosyaları Yükle" }); } })(window.kendo.jQuery);
export default (state = [], action) => { switch (action.type) { case 'INIT_WEB3': return action.payload default: return state } }
$(document).on("change","#image1",function(){var n,t;let i=$(this).parent().attr("id");(console.log(i),console.log(1),n=!this.files?[]:this.files,n.length&&window.FileReader)&&(/^image/.test(n[0].type)?(t=new FileReader,t.readAsDataURL(n[0]),t.onloadend=function(){$("#"+i).css("background-image","url("+this.result+")")}):alert("Upload an image"))});
const puppeteer = require('puppeteer'); const catchAsync = fn => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(err => next(err)); }; exports.printResume = catchAsync(async (req, res) =>{ const userId = req.query.userId; const auth = req.query.auth; const type = req.query.type; const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'], }); const page = await browser.newPage(); const url = `http://localhost:8000/app/preview?userId=${userId}&auth=${auth}`; //await page.goto(`${url}`, {waitUntil: 'networkidle0'}); await page.goto(`${url}`, {waitUntil: 'load'}); await page.emulateMediaType('print'); let pdf; if (type === 'single') { const height = await page.evaluate(() => { const { body } = document; const html = document.documentElement; const maxHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight, ); return maxHeight; }); pdf = await page.pdf({ printBackground: true, width: `21cm`, height: `${height}px`, pageRanges: '1', }); } else { pdf = await page.pdf({ format: 'A4', printBackground: true, }); } await browser.close(); return res.status(200).json({ 'data': Buffer.from(pdf).toString('base64') }) })
const connectionPool = require('./mysqlConnectionPool') const { errorCodes } = require('./errorCodes') const token = { addToken: (isAdmin, expiresAt, userId, clientId) => { return new Promise((resolve, reject) => { connectionPool.query(`INSERT INTO tokens(is_admin, expires_at, client_id, user_id) VALUES (${isAdmin}, ${expiresAt}, \'${clientId}\', ${userId}) ON DUPLICATE KEY UPDATE expires_at = ${expiresAt}`, (error, results, fields) => { if(error) { return reject({ type: errorCodes.DBERR, details: error }) } else { return resolve({ is_admin: isAdmin, client_id: clientId, user_id: userId }) } }) }) } } module.exports = token
import React from 'react'; import Helmet from 'react-helmet'; import Fonts from '../components/Fonts'; const PageWrapper = ({ children }) => ( <div> <Helmet title="Alexander Madyankin" meta={[ { name: 'description', content: 'Alexander Madyankin. Frontend developer', }, ]} /> <Fonts /> <div>{children()}</div> </div> ); export default PageWrapper;
import typescript from "rollup-plugin-typescript2"; import json from "rollup-plugin-json"; // import resolve from "@rollup/plugin-node-resolve"; export default { external: ["@valeera/eventdispatcher", "@valeera/idgenerator"], input: "src/index.ts", output: [ { file: "build/x.js", format: "umd", globals: { "@valeera/eventdispatcher": "EventDispatcher", "@valeera/idgenerator": "IdGenerator" }, indent: "\t", name: "X", sourcemap: true }, { file: "build/x.module.js", format: "es", indent: "\t", sourcemap: false } ], plugins: [ json(), typescript({ tsconfig: "./tsconfig.json" }) ] };
export function readStoryNote(btn) { btn.addEventListener("click", (event) => { const txt = event.target.dataset.note; if (txt.length >= 1) { const utterance = new SpeechSynthesisUtterance(txt); window.speechSynthesis.speak(utterance); } }) }
/* * My97 DatePicker 4.8 * License: http://www.my97.net/license.asp */ var $dp,WdatePicker;(function(){var l={ $langList:[ {name:"en",charset:"UTF-8"}, {name:"zh-cn",charset:"gb2312"}, {name:"zh-tw",charset:"GBK"} ], $skinList:[ {name:"default",charset:"gb2312"}, {name:"whyGreen",charset:"gb2312"}, {name:"blue",charset:"gb2312"}, {name:"green",charset:"gb2312"}, {name:"simple",charset:"gb2312"}, {name:"ext",charset:"gb2312"}, {name:"blueFresh",charset:"gb2312"}, {name:"twoer",charset:"gb2312"}, {name:"YcloudRed",charset:"gb2312"}], $wdate:true, $crossFrame:false, $preLoad:false, $dpPath:"", doubleCalendar:false, enableKeyboard:true, enableInputMask:true, autoUpdateOnChanged:null, weekMethod:"MSExcel", position:{}, lang:"auto", skin:"default", dateFmt:"yyyy-MM-dd", realDateFmt:"yyyy-MM-dd", realTimeFmt:"HH:mm:ss", realFullFmt:"%Date %Time", minDate:"0001-01-01 00:00:00", maxDate:"9999-12-31 23:59:59", minTime:"00:00:00", maxTime:"23:59:59", startDate:"", alwaysUseStartDate:false, yearOffset:1911, firstDayOfWeek:0, isShowWeek:false, highLineWeekDay:true, isShowClear:true, isShowToday:true, isShowOK:true, isShowOthers:true, readOnly:false, errDealMode:0, autoPickDate:null, qsEnabled:true, autoShowQS:false, hmsMenuCfg:{H:[1,6],m:[5,6],s:[15,4]}, opposite:false,specialDates:null,specialDays:null,disabledDates:null,disabledDays:null,onpicking:null,onpicked:null,onclearing:null,oncleared:null,ychanging:null,ychanged:null,Mchanging:null,Mchanged:null,dchanging:null,dchanged:null,Hchanging:null,Hchanged:null,mchanging:null,mchanged:null,schanging:null,schanged:null,eCont:null,vel:null,elProp:"",errMsg:"",quickSel:[],has:{},getRealLang:function(){var d=l.$langList;for(var e=0;e<d.length;e++){if(d[e].name==this.lang){return d[e]}}return d[0]}};WdatePicker=g;var n=window,i={innerHTML:""},z="document",B="documentElement",H="getElementsByTagName",E,u,h,f,D;var v=navigator.appName;if(v=="Microsoft Internet Explorer"){h=true}else{if(v=="Opera"){D=true}else{f=true}}u=l.$dpPath||q();if(l.$wdate){m(u+"skin/WdatePicker.css")}E=n;if(l.$crossFrame){try{while(E.parent!=E&&E.parent[z][H]("frameset").length==0){E=E.parent}}catch(y){}}if(!E.$dp){E.$dp={ff:f,ie:h,opera:D,status:0,defMinDate:l.minDate,defMaxDate:l.maxDate}}b();if(l.$preLoad&&$dp.status==0){k(n,"onload",function(){g(null,true)})}if(!n[z].docMD){k(n[z],"onmousedown",s,true);n[z].docMD=true}if(!E[z].docMD){k(E[z],"onmousedown",s,true);E[z].docMD=true}k(n,"onunload",function(){if($dp.dd){r($dp.dd,"none")}});function b(){try{E[z],E.$dp=E.$dp||{}}catch(I){E=n;$dp=$dp||{}}var w={win:n,$:function(e){return(typeof e=="string")?n[z].getElementById(e):e},$D:function(J,e){return this.$DV(this.$(J).value,e)},$DV:function(J,e){if(J!=""){this.dt=$dp.cal.splitDate(J,$dp.cal.dateFmt);if(e){for(var L in e){if(this.dt[L]===undefined){this.errMsg="invalid property:"+L}else{this.dt[L]+=e[L];if(L=="M"){var M=e.M>0?1:0;var K=new Date(this.dt.y,this.dt.M,0).getDate();this.dt.d=Math.min(K+M,this.dt.d)}}}}if(this.dt.refresh()){return this.dt}}return""},show:function(){var K=E[z].getElementsByTagName("div"),J=100000;for(var e=0;e<K.length;e++){var L=parseInt(K[e].style.zIndex);if(L>J){J=L}}this.dd.style.zIndex=J+2;r(this.dd,"block");r(this.dd.firstChild,"")},unbind:function(e){e=this.$(e);if(e.initcfg){t(e,"onclick",function(){g(e.initcfg)});t(e,"onfocus",function(){g(e.initcfg)})}},hide:function(){r(this.dd,"none")},attachEvent:k};for(var d in w){E.$dp[d]=w[d]}$dp=E.$dp}function k(I,J,w,d){if(I.addEventListener){var e=J.replace(/on/,"");w._ieEmuEventHandler=function(K){return w(K)};I.addEventListener(e,w._ieEmuEventHandler,d)}else{I.attachEvent(J,w)}}function t(w,I,e){if(w.removeEventListener){var d=I.replace(/on/,"");e._ieEmuEventHandler=function(J){return e(J)};w.removeEventListener(d,e._ieEmuEventHandler,false)}else{w.detachEvent(I,e)}}function C(w,e,d){if(typeof w!=typeof e){return false}if(typeof w=="object"){if(!d){for(var I in w){if(typeof e[I]=="undefined"){return false}if(!C(w[I],e[I],true)){return false}}}return true}else{if(typeof w=="function"&&typeof e=="function"){return w.toString()==e.toString()}else{return w==e}}}function q(){var I,w,d=n[z][H]("script");for(var e=0;e<d.length;e++){I=d[e].getAttribute("src")||"";I=I.substr(0,I.toLowerCase().indexOf("wdatepicker.js"));var w=I.lastIndexOf("/");if(w>0){I=I.substring(0,w+1)}if(I){break}}return I}function m(w,I,J){var d=n[z][H]("HEAD").item(0),e=n[z].createElement("link");if(d){e.href=w;e.rel="stylesheet";e.type="text/css";if(I){e.title=I}if(J){e.charset=J}d.appendChild(e)}}function p(I){I=I||E;var L=0,d=0;while(I!=E){var N=I.parent[z][H]("iframe");for(var J=0;J<N.length;J++){try{if(N[J].contentWindow==I){var K=o(N[J]);L+=K.left;d+=K.top;break}}catch(M){}}I=I.parent}return{leftM:L,topM:d}}function o(I,w){if(I.getBoundingClientRect){return I.getBoundingClientRect()}else{var J={ROOT_TAG:/^body|html$/i,OP_SCROLL:/^(?:inline|table-row)$/i};var e=false,M=null,P=I.offsetTop,K=I.offsetLeft,d=I.offsetWidth,O=I.offsetHeight;var L=I.offsetParent;if(L!=I){while(L){K+=L.offsetLeft;P+=L.offsetTop;if(c(L,"position").toLowerCase()=="fixed"){e=true}else{if(L.tagName.toLowerCase()=="body"){M=L.ownerDocument.defaultView}}L=L.offsetParent}}L=I.parentNode;while(L.tagName&&!J.ROOT_TAG.test(L.tagName)){if(L.scrollTop||L.scrollLeft){if(!J.OP_SCROLL.test(r(L))){if(!D||L.style.overflow!=="visible"){K-=L.scrollLeft;P-=L.scrollTop}}}L=L.parentNode}if(!e){var N=F(M);K-=N.left;P-=N.top}d+=K;O+=P;return{left:K,top:P,right:d,bottom:O}}}function x(e){e=e||E;var J=e[z],I=(e.innerWidth)?e.innerWidth:(J[B]&&J[B].clientWidth)?J[B].clientWidth:J.body.offsetWidth,d=(e.innerHeight)?e.innerHeight:(J[B]&&J[B].clientHeight)?J[B].clientHeight:J.body.offsetHeight;return{width:I,height:d}}function F(e){e=e||E;var J=e[z],d=J[B],I=J.body;J=(d&&d.scrollTop!=null&&(d.scrollTop>I.scrollTop||d.scrollLeft>I.scrollLeft))?d:I;return{top:J.scrollTop,left:J.scrollLeft}}function s(d){try{var w=d?(d.srcElement||d.target):null;if($dp.cal&&!$dp.eCont&&$dp.dd&&w!=$dp.el&&$dp.dd.style.display=="block"){$dp.cal.close()}}catch(d){}}function A(){$dp.status=2}var G,j;function g(M,d){if(!$dp){return}b();var J={};for(var L in M){J[L]=M[L]}for(var L in l){if(L.substring(0,1)!="$"&&J[L]===undefined){J[L]=l[L]}}if(d){if(!w()){j=j||setInterval(function(){if(E[z].readyState=="complete"){clearInterval(j)}g(null,true)},50);return}if($dp.status==0){$dp.status=1;J.el=i;a(J,true)}else{return}}else{if(J.eCont){J.eCont=$dp.$(J.eCont);J.el=i;J.autoPickDate=true;J.qsEnabled=false;a(J)}else{if(l.$preLoad&&$dp.status!=2){return}var I=N();if(n.event===I||I){J.srcEl=I.srcElement||I.target;I.cancelBubble=true}J.el=J.el=$dp.$(J.el||J.srcEl);if(J.el==null){alert("WdatePicker:el is null!\nexample:onclick=\"WdatePicker({el:this})\"");return;}try{if(!J.el||J.el.My97Mark===true||J.el.disabled||($dp.dd&&r($dp.dd)!="none"&&$dp.dd.style.left!="-970px")){if(J.el.My97Mark){J.el.My97Mark=false}return}}catch(K){}if(I&&J.el.nodeType==1&&!C(J.el.initcfg,M)){$dp.unbind(J.el);k(J.el,I.type=="focus"?"onclick":"onfocus",function(){g(M)});J.el.initcfg=M}a(J)}}function w(){if(h&&E!=n&&E[z].readyState!="complete"){return false}return true}function N(){if(f){try{func=N.caller;while(func!=null){var O=func.arguments[0];if(O&&(O+"").indexOf("Event")>=0){return O}func=func.caller}}catch(P){}return null}return event}}function c(e,d){return e.currentStyle?e.currentStyle[d]:document.defaultView.getComputedStyle(e,false)[d]}function r(e,d){if(e){if(d!=null){e.style.display=d}else{return c(e,"display")}}}function a(e,d){var K=e.el?e.el.nodeName:"INPUT";if(d||e.eCont||new RegExp(/input|textarea|div|span|p|a/ig).test(K)){e.elProp=K=="INPUT"?"value":"innerHTML"}else{return}if(e.lang=="auto"){e.lang=h?navigator.browserLanguage.toLowerCase():navigator.language.toLowerCase()}if(!e.eCont){for(var J in e){$dp[J]=e[J]}}if(!$dp.dd||e.eCont||($dp.dd&&(e.getRealLang().name!=$dp.dd.lang||e.skin!=$dp.dd.skin))){if(e.eCont){w(e.eCont,e)}else{$dp.dd=E[z].createElement("DIV");$dp.dd.style.cssText="position:absolute";E[z].body.appendChild($dp.dd);w($dp.dd,e);if(d){$dp.dd.style.left=$dp.dd.style.top="-970px"}else{$dp.show();I($dp)}}}else{if($dp.cal){$dp.show();$dp.cal.init();if(!$dp.eCont){I($dp)}}}function w(V,P){var O=E[z].domain,S=false,M='<iframe hideFocus=true width=9 height=7 frameborder=0 border=0 scrolling=no src="about:blank"></iframe>';V.innerHTML=M;var L=l.$langList,U=l.$skinList,T;try{T=V.lastChild.contentWindow[z]}catch(Q){S=true;V.removeChild(V.lastChild);var N=E[z].createElement("iframe");N.hideFocus=true;N.frameBorder=0;N.scrolling="no";N.src="javascript:(function(){var d=document;d.open();d.domain='"+O+"';})()";V.appendChild(N);setTimeout(function(){T=V.lastChild.contentWindow[z];R()},97);return}R();function R(){var Y=P.getRealLang();V.lang=Y.name;V.skin=P.skin;var X=["<head><script>","","var doc=document, $d, $dp, $cfg=doc.cfg, $pdp = parent.$dp, $dt, $tdt, $sdt, $lastInput, $IE=$pdp.ie, $FF = $pdp.ff,$OPERA=$pdp.opera, $ny, $cMark = false;","if($cfg.eCont){$dp = {};for(var p in $pdp)$dp[p]=$pdp[p];}else{$dp=$pdp;};for(var p in $cfg){$dp[p]=$cfg[p];}","doc.oncontextmenu=function(){try{$c._fillQS(!$dp.has.d,1);showB($d.qsDivSel);}catch(e){};return false;};","<\/script><script src=",u,"lang/",Y.name,".js charset=",Y.charset,"><\/script>"];if(S){X[1]='document.domain="'+O+'";'}for(var W=0;W<U.length;W++){if(U[W].name==P.skin){X.push('<link rel="stylesheet" type="text/css" href="'+u+"skin/"+U[W].name+'/datepicker.css" charset="'+U[W].charset+'"/>')}}X.push('<script src="'+u+'calendar.js"><\/script>');X.push('</head><body leftmargin="0" topmargin="0" tabindex=0></body></html>');X.push('<script>var t;t=t||setInterval(function(){if((typeof(doc.ready)=="boolean"&&doc.ready)||doc.readyState=="complete"){new My97DP();$cfg.onload();$c.autoSize();$cfg.setPos($dp);clearInterval(t);}},20);<\/script>');P.setPos=I;P.onload=A;T.write("<html>");T.cfg=P;T.write(X.join(""));T.close()}}function I(O){var M=O.position.left,V=O.position.top,L=O.el;if(L==i){return}if(L!=O.srcEl&&(r(L)=="none"||L.type=="hidden")){L=O.srcEl}var T=o(L),P=p(n),U=x(E),Q=F(E),N=$dp.dd.offsetHeight,S=$dp.dd.offsetWidth;if(isNaN(V)){V=0}if((P.topM+T.bottom+N>U.height)&&(P.topM+T.top-N>0)){V+=Q.top+P.topM+T.top-N-2}else{V+=Q.top+P.topM+T.bottom;var R=V-Q.top+N-U.height;if(R>0){V-=R}}if(isNaN(M)){M=0}M+=Q.left+Math.min(P.leftM+T.left,U.width-S-5)-(h?2:0);O.dd.style.top=V+"px";O.dd.style.left=M+"px"}}})();
(self.webpackChunkgeonode_mapstore_client=self.webpackChunkgeonode_mapstore_client||[]).push([[6235],{965539:(e,t,n)=>{"use strict";n.d(t,{Z:()=>s});var r=n(667294),o=n.n(r);function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?i(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const s=function(e){var t=e.id,n=e.children,r=e.header,i=e.footer,a=e.columns,s=e.height,l=e.style,u=void 0===l?{}:l,p=e.className,d=e.bodyClassName,f=void 0===d?"ms2-border-layout-body":d;return o().createElement("div",{id:t,className:p,style:c({display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden"},u)},r,o().createElement("div",{className:f,style:{display:"flex",flex:1,overflowY:"auto"}},o().createElement("main",{className:"ms2-border-layout-content",style:{flex:1}},s?o().createElement("div",{style:{height:s}},n):n),s?o().createElement("div",{style:{height:s}},a):a),i)}},416919:(e,t,n)=>{"use strict";n.d(t,{Z:()=>d});var r=n(667294),o=n.n(r),i=n(732833),c=n(965539),a=n(418093),s=n(757588),l=n(282467),u={bottom:{true:"chevron-down",false:"chevron-up"},top:{true:"chevron-up",false:"chevron-down"},right:{true:"chevron-right",false:"chevron-left"},left:{true:"chevron-left",false:"chevron-right"}};const p=function(e){var t=e.position,n=void 0===t?"right":t,r=e.onClose,i=e.bsStyle,c=void 0===i?"default":i,a=e.title,p=void 0===a?"":a,d=e.fullscreen,f=void 0!==d&&d,m=e.showFullscreen,v=void 0!==m&&m,y=e.glyph,g=void 0===y?"info-sign":y,h=e.additionalRows,b=e.onFullscreen,w=void 0===b?function(){}:b,E=r?o().createElement(l.Z,{key:"ms-header-close",className:"square-button ms-close",onClick:r,bsStyle:c},o().createElement(s.Glyphicon,{glyph:"1-close"})):null,S=v?o().createElement(l.Z,{key:"ms-header-glyph",className:"square-button",bsStyle:c,onClick:function(){return w(!f)}},o().createElement(s.Glyphicon,{glyph:u[n]&&u[n][f]||"resize-full"})):o().createElement("div",{key:"ms-header-glyph",className:"square-button ".concat("bg-"+c),style:{display:"flex"}},o().createElement(s.Glyphicon,{glyph:g,className:"".concat("default"===c?"text-primary":"")})),O="left"===n?[E,S]:[S,E];return o().createElement(s.Grid,{fluid:!0,style:{width:"100%"},className:"ms-header ms-"+c},o().createElement(s.Row,null,o().createElement(s.Col,{xs:2},O[0]),o().createElement(s.Col,{xs:8},o().createElement("h4",null,p)),o().createElement(s.Col,{xs:2},O[1])),h)},d=(0,a.withState)("fullscreen","onFullscreen",!1)((function(e){var t=e.fluid,n=e.className,r=void 0===n?"":n,a=e.fullscreen,s=void 0!==a&&a,l=e.position,u=e.open,d=e.size,f=void 0===d?550:d,m=e.style,v=void 0===m?{}:m,y=e.zIndex,g=void 0===y?1030:y,h=e.onClose,b=e.bsStyle,w=e.title,E=e.showFullscreen,S=void 0!==E&&E,O=e.glyph,P=e.header,j=e.footer,x=e.children,C=e.onFullscreen,I=void 0===C?function(){}:C,k=e.fixed,M=void 0!==k&&k,z=e.resizable,N=void 0!==z&&z,T=e.hideHeader;return o().createElement("div",{className:"ms-side-panel "+(M?"":"ms-absolute-dock ")+(N?"":"react-dock-no-resize ")+r},o().createElement(i.default,{fluid:t||s,position:l,dimMode:"none",isVisible:u,size:s?1:f,dockStyle:v,zIndex:g},o().createElement(c.Z,{header:!T&&u&&o().createElement(p,{position:l,onClose:h,bsStyle:b,title:w,fullscreen:s,showFullscreen:S,glyph:O,additionalRows:P,onFullscreen:I}),footer:u&&j},u&&x)))}))},632107:(e,t,n)=>{"use strict";n.d(t,{Z:()=>p});var r=n(667294),o=n.n(r),i=n(418093),c=n(965539),a=n(416919),s=n(694745),l=["children","header"];var u=(0,i.renameProps)({open:"show"})((function(e){var t=e.children,n=e.header,r=function(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}(e,l);return o().createElement(s.Z,r,o().createElement(c.Z,{header:o().createElement("div",{className:"ms-header"},n)},t))}));const p=(0,i.branch)((function(e){return!e.dock}),(function(){return function(e){return o().createElement(u,e)}}))(a.Z)},822780:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Support:()=>ne,default:()=>ie});var r=n(667294),o=n.n(r),i=n(533664),c=n(22222),a=n(675110),s=n(671314),l=n(727418),u=n.n(l),p="SWIPE:SET_ACTIVE",d="SWIPE:SET_MODE",f="SWIPE:SET_SWIPE_TOOL_DIRECTION",m="SWIPE:SET_SPY_TOOL_RADIUS";function v(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"active";return{type:p,active:e,prop:t}}function y(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function g(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?y(Object(n),!0).forEach((function(t){h(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):y(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function h(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var b=n(989255),w=n(580416),E=n(275982);const S={resetLayerSwipeSettingsEpic:function(e,t){return e.ofType(w.c7).switchMap((function(e){var n=e.nodeType,r=t.getState();return(0,s.yn)(r).active&&"group"===n?b.Observable.of(v(!1)):b.Observable.empty()}))},deactivateSwipeToolOnSwitchMaps:function(e,t){return e.ofType(E.nk).switchMap((function(){return(0,s.yn)(t.getState()).active?b.Observable.of(v(!1)):b.Observable.empty()}))}};var O=n(322843),P=n(743129),j=n(185552),x=n.n(j),C=n(313311),I=n.n(C),k=n(805346),M=n(632107);function z(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function N(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?z(Object(n),!0).forEach((function(t){T(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):z(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function T(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var R=[{label:"Horizontal",value:"cut-horizontal"},{label:"Vertical",value:"cut-vertical"}],D=function(e){var t=e.spyModeSettings,n=e.onSetSpyToolRadius;return o().createElement("div",{className:"mapstore-swipe-settings-spy"},o().createElement("h4",null,o().createElement(k.Z,{msgId:"toc.radius"})),o().createElement("div",{className:"mapstore-slider with-tooltip"},o().createElement(x(),{tooltips:!0,step:10,start:[t.radius],range:{min:[20],max:[100]},onChange:function(e){return n(e[0])}})))},A=function(e){var t=e.swipeModeSettings,n=e.onSetSwipeToolDirection;return o().createElement("div",{className:"mapstore-swipe-settings-slider"},o().createElement("h4",null,o().createElement(k.Z,{msgId:"toc.direction"})),o().createElement(P.ZP,{styles:{menuPortal:function(e){return N(N({},e),{},{zIndex:3100})}},onChange:function(e){var t=e.value;return n(t)},clearable:!1,value:I()(R,["value",t.direction]),options:R}))},Z=(0,c.P1)([s.yn,s.wQ,s.IY],(function(e,t,n){return{configuring:(null==e?void 0:e.configuring)||!1,toolMode:(null==e?void 0:e.mode)||"swipe",swipeModeSettings:t,spyModeSettings:n}}));const L=(0,i.connect)(Z,{onSetConfigurationActive:v,onSetSwipeToolDirection:function(e){return{type:f,direction:e}},onSetSpyToolRadius:function(e){return{type:m,radius:e}}})((function(e){var t=e.configuring,n=e.toolMode,r=e.swipeModeSettings,i=e.spyModeSettings,c=e.onSetConfigurationActive,a=void 0===c?function(){}:c,s=e.onSetSpyToolRadius,l=void 0===s?function(){}:s,u=e.onSetSwipeToolDirection,p=void 0===u?function(){}:u;return o().createElement("div",{className:"mapstore-swipe-settings"},o().createElement(M.Z,{title:"spy"===n?o().createElement(k.Z,{msgId:"toc.spyconfiguration"}):o().createElement(k.Z,{msgId:"toc.swipeconfiguration"}),open:t,onClose:function(){return a(!1,"configuring")},enableFooter:!1,draggable:!0,size:"xs",bodyClassName:"mapstore-swipe-setiings-modal-body",dialogClassName:" mapstore-swipe-settings-modal",glyph:"transfer"},"spy"===n?o().createElement(D,{spyModeSettings:i,onSetSpyToolRadius:l}):o().createElement(A,{swipeModeSettings:r,onSetSwipeToolDirection:p})))}));var _=n(757588),G=n(485294),Y=n.n(G);const F=function(e){var t=e.map,n=e.layer,o=e.type,i=e.getWidth,c=e.getHeight,a=e.circleCutProp,s=(0,r.useCallback)((function(e){var n=e.context,r=i()*t.pixelRatio_;n.save(),n.beginPath(),n.rect(r,0,n.canvas.width-r,n.canvas.height),n.strokeStyle="rgba(0,0,0,0.5)",n.clip()}),[n,o]),l=(0,r.useCallback)((function(e){e.context.restore()}),[n,o]),u=(0,r.useCallback)((function(e){var n=e.context,r=c()*t.pixelRatio_;n.save(),n.beginPath(),n.rect(0,r,n.canvas.width,n.canvas.height-r),n.clip()}),[n,o]),p=(0,r.useCallback)((function(e){var t=e.context,n=e.frameState.pixelRatio;t.save(),t.beginPath();var r=a.getMousePosition();r&&(t.arc(r[0]*n,r[1]*n,a.radius*n,0,2*Math.PI),t.lineWidth=5*n,t.strokeStyle="rgba(0,0,0,0.5)",t.stroke()),t.clip()}),[n,o,a]);return(0,r.useEffect)((function(){var e=t.getLayers().getArray().filter((function(e){return e.get("msId")===n}))[0];if(e){switch(o){case"cut-vertical":!function(e,t,n){e.on("precompose",t),e.on("postcompose",n)}(e,s,l);break;case"cut-horizontal":!function(e,t,n){e.on("precompose",t),e.on("postcompose",n)}(e,u,l);break;case"circle":!function(e,t,n){e.on("precompose",t),e.on("postcompose",n)}(e,p,l)}return t.render(),function(){e.un("precompose",s),e.un("precompose",u),e.un("precompose",p),e.un("postcompose",l),t.render()}}return function(){return t.render()}}),[n,o,a]),null};function W(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,i=[],c=!0,a=!1;try{for(n=n.call(e);!(c=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);c=!0);}catch(e){a=!0,o=e}finally{try{c||null==n.return||n.return()}finally{if(a)throw o}}return i}}(e,t)||function(e,t){if(e){if("string"==typeof e)return q(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?q(e,t):void 0}}(e,t)||function(){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 q(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var H=function(e){var t=e.type,n=e.map,i=e.widthRef,c=W((0,r.useState)(),2),a=c[0],s=c[1],l=W((0,r.useState)(!0),2),u=l[0],p=l[1],d=function(){s({x:0,y:0}),i.current=n.getProperties().size[0]/2};return(0,r.useEffect)((function(){return window.addEventListener("resize",d),function(){window.removeEventListener("resize",d)}}),[t]),(0,r.useEffect)((function(){i.current=n.getProperties().size[0]/2}),[t]),o().createElement(Y(),{position:a,bounds:"parent",onStart:function(){return p(!1)},onDrag:function(e,t){return function(e,t){i.current+=t.deltaX,s({x:t.x,y:t.y}),n.render()}(0,t)},onStop:function(){return p(!0)}},o().createElement("div",{className:"mapstore-swipe-slider",style:{height:"100%",top:"0px",left:"".concat(n.getProperties().size[0]/2,"px"),width:"8px",cursor:"col-resize"}},u&&o().createElement("div",{className:"ms-vertical-swipe-slider-arrows",style:{top:"".concat(n.getProperties().size[1]/2-26,"px")}},o().createElement("div",{className:"ms-slider-arrows"},o().createElement(_.Glyphicon,{glyph:"chevron-left"})),o().createElement("div",{className:"ms-slider-arrows"},o().createElement(_.Glyphicon,{glyph:"chevron-right"})))))},Q=function(e){var t=e.type,n=e.map,i=e.heightRef,c=W((0,r.useState)(),2),a=c[0],s=c[1],l=W((0,r.useState)(!0),2),u=l[0],p=l[1],d=function(){s({x:0,y:0}),i.current=n.getProperties().size[1]/2};return(0,r.useEffect)((function(){return window.addEventListener("resize",d),function(){window.removeEventListener("resize",d)}}),[t]),(0,r.useEffect)((function(){i.current=n.getProperties().size[1]/2}),[t]),o().createElement(Y(),{position:a,bounds:"parent",onStart:function(){return p(!1)},onDrag:function(e,t){return function(e,t){i.current+=t.deltaY,s({x:t.x,y:t.y}),n.render()}(0,t)},onStop:function(){return p(!0)}},o().createElement("div",{className:"mapstore-swipe-slider",style:{height:"8px",top:"".concat(n.getProperties().size[1]/2,"px"),left:"0px",width:"100%",cursor:"row-resize"}},u&&o().createElement("div",{className:"ms-horizontal-swipe-slider-arrows",style:{left:"".concat(n.getProperties().size[0]/2-26,"px")}},o().createElement("div",{className:"ms-slider-arrows"},o().createElement(_.Glyphicon,{glyph:"chevron-up"})),o().createElement("div",{className:"ms-slider-arrows"},o().createElement(_.Glyphicon,{glyph:"chevron-down"})))))};const V=function(e){var t=e.map,n=e.layer,i=e.type,c=void 0===i?"cut-vertical":i,a=e.active,s=(0,r.useRef)(),l=(0,r.useRef)();return n&&a?o().createElement(o().Fragment,null,"cut-vertical"===c&&o().createElement(H,{widthRef:l,map:t,type:c}),"cut-horizontal"===c&&o().createElement(Q,{heightRef:s,map:t,type:c}),o().createElement(F,{map:t,layer:n,type:c,getWidth:function(){return l.current},getHeight:function(){return s.current}})):null},U=function(e){var t=e.layer,n=e.map,i=e.active,c=e.radius,a=(0,r.useRef)(),s=(0,r.useCallback)((function(e){a.current=n.getEventPixel(e),n.render()}),[t,c]),l=(0,r.useCallback)((function(){a.current=null,n.render()}),[t,c]);(0,r.useEffect)((function(){var e=n.getTargetElement();return e.addEventListener("mousemove",s),e.addEventListener("mouseout",l),function(){e.removeEventListener("mousemove",s),e.removeEventListener("mouseout",l)}}),[]);var u={radius:c,getMousePosition:function(){return a.current}};return t&&i?o().createElement(F,{map:n,layer:t,type:"circle",circleCutProp:u}):null};var B=n(675263),X=n.n(B);function $(){return $=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},$.apply(this,arguments)}var J=(0,n(815135).Z)(_.SplitButton),K={title:o().createElement(_.Glyphicon,{glyph:"transfer"}),tooltipId:"toc.compareTool",tooltipPosition:"top",className:"square-button-md no-border",pullRight:!0},ee=function(e){var t=e.swipeSettings,n=e.onSetActive,r=e.onSetSwipeMode,i=e.status;return o().createElement(J,$({onClick:function(){t.active||"LAYER"!==i?n(!1):n(!0)},bsStyle:null!=t&&t.active?"success":"primary"},K),o().createElement(_.MenuItem,{active:"swipe"===(null==t?void 0:t.mode),onClick:function(){r("swipe"),n(!0)}},o().createElement(_.Glyphicon,{glyph:"vert-dashed"}),o().createElement(k.Z,{msgId:"toc.swipe"})),o().createElement(_.MenuItem,{active:"spy"===(null==t?void 0:t.mode),onClick:function(){r("spy"),n(!0)}},o().createElement(_.Glyphicon,{glyph:"search"}),o().createElement(k.Z,{msgId:"toc.spyGlass"})),o().createElement(_.MenuItem,{onClick:function(){t.configuring||"LAYER"!==i?n(!1,"configuring"):n(!0,"configuring")}},o().createElement(_.Glyphicon,{glyph:"cog"}),o().createElement(k.Z,{msgId:"toc.configureTool"})))};ee.propTypes={swipeSettings:X().object,status:X().string,onSetActive:X().func,onSetSwipeMode:X().func},ee.defaultProps={status:"LAYER",onSetSwipeMode:function(){},onSetActive:function(){}};const te=ee;var ne=function(e){var t=e.mode,n=e.map,r=e.layer,i=e.active,c=e.swipeModeSettings,a=e.spyModeSettings;return"spy"===t?o().createElement(U,{map:n,layer:r,active:i,radius:a.radius}):o().createElement(V,{map:n,layer:r,active:i,type:c.direction})},re=(0,c.P1)([a.Iz,s.yn,s.wQ,s.IY],(function(e,t,n,r){return{layer:null==e?void 0:e.id,active:t.active||!1,swipeModeSettings:n,spyModeSettings:r,mode:(null==t?void 0:t.mode)||"swipe"}})),oe=(0,i.connect)(re,null)(ne);const ie=(0,O.rx)("Swipe",{options:{disablePluginIf:"{state('mapType') === 'leaflet' || state('mapType') === 'cesium'}"},component:L,containers:{TOC:{name:"Swipe",target:"toolbar",selector:function(e){return"LAYER"===e.status},Component:(0,i.connect)((0,c.P1)(s.yn,(function(e){return{swipeSettings:e}})),{onSetActive:v,onSetSwipeMode:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"swipe";return{type:d,mode:e}}})(te)},Map:{name:"Swipe",Tool:oe}},reducers:{swipe:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case p:return u()({},e,h({},t.prop,t.active));case d:return u()({},e,{mode:t.mode});case f:var n=g(g({},e.swipe),{},{direction:t.direction});return u()({},e,{swipe:n});case m:var r=g(g({},e.spy),{},{radius:t.radius});return u()({},e,{spy:r});default:return e}}},epics:S})},671314:(e,t,n)=>{"use strict";n.d(t,{yn:()=>r,IY:()=>o,wQ:()=>i});var r=function(e){return e.swipe&&e.swipe||{active:!1}},o=function(e){var t;return(null==e||null===(t=e.swipe)||void 0===t?void 0:t.spy)||{radius:80}},i=function(e){var t;return(null==e||null===(t=e.swipe)||void 0===t?void 0:t.swipe)||{direction:"cut-vertical"}}},819081:(e,t,n)=>{"use strict";e.exports=n(1174)}}]);
const db = require("../database/database"); const WEB_HOST = process.env.WEB_HOST exports.getRegistrationRequests = async (req, res, next) => { try{ const registrationRequests = await db.getAllRegistrationRequests() console.log(registrationRequests) return res.status(200).json(registrationRequests) } catch(err){ next(err) } } exports.registerUser = async (req, res, next) => { try{ const {username, password, githubUrl, profileImageUrl} = req.body; if(!username || !password || !githubUrl || !profileImageUrl) return res.status(400).send("Missing Fields") await db.registerRequest(username, password, githubUrl, profileImageUrl) res.status(200).send("success") } catch(err){ next(err) } } exports.approveRegisterUser = async (req, res, next) => { try{ const { RegisterID } = req.params; await db.approveRegisterRequest(RegisterID) return res.status(200).send("success") } catch(err){ next(err) } } exports.rejectRegisterUser = async (req, res, next) => { try{ const { RegisterID } = req.params; await db.rejectRegisterRequest(RegisterID) return res.status(200).send("success") } catch(err){ next(err) } }
var D3 = D3 || {}; D3.Text = function () { function calcFontSizeRaw(text, radius, minimumSize, isMultiline) { minimumSize = minimumSize || 10; var textSize = radius / 3; if (typeof text === "string") { var len = text.substring(0, radius / 3).length + 1.5; textSize *= 10 / len; textSize += 1; // experimental alternative method: // var textSize = 3.3 * radius / text.length; // Tweak for Indian scripts and CJK ones if (text.match(/[\u0900-\u0DFF\u1100-\u11FF\u2E80-\u2EFF\u3000-\u9FFF]/)) { textSize *= 0.6; } if (textSize < minimumSize) { textSize = minimumSize; } /* Disabled for the time being, better without this if (isMultiline) { var numWords = text.split(/\s+/).length; if (numWords > 1) { if (numWords > 4) { numWords = 4; } textSize += textSize * (4 - numWords) * 0.1; } } */ return Math.round(textSize); } if (textSize < minimumSize) { textSize = minimumSize; } return Math.round(textSize); } function calcFontSize(text, radius, minimumSize, isMultiline) { return calcFontSizeRaw(text, radius, minimumSize, isMultiline) + 'px'; } function getTextWithElipsisIfNeeded(str, threshold) { if (typeof str === "string") { if (str.length > threshold) { return str.substring(0, threshold - 3) + "..."; } } return str; } return { calcFontSizeRaw: calcFontSizeRaw, calcFontSize: calcFontSize, getTextWithElipsisIfNeeded: getTextWithElipsisIfNeeded }; }(); D3.Transition = function () { function fadeIn(sel, duration) { sel.style("opacity", 0.0) .transition() .duration(duration) .style("opacity", 1.0); } function fadeOut(sel, duration) { sel.style("opacity", 1.0) .transition() .duration(duration) .style("opacity", 0.0); } return { fadeIn: fadeIn, fadeOut: fadeOut }; }(); D3.Click = function () { function delayDblClick() { var event = d3.dispatch('click', 'dblclick'); function cc(selection) { var down, tolerance = 5, last, wait = null; // euclidean distance function dist(a, b) { return Math.sqrt(Math.pow(a[0] - b[0], 2), Math.pow(a[1] - b[1], 2)); } selection.on('mousedown', function () { down = d3.mouse(document.body); last = +new Date(); }); selection.on('mouseup', function (d) { if (dist(down, d3.mouse(document.body)) > tolerance) { return; } else { if (wait) { window.clearTimeout(wait); wait = null; event.dblclick(d); } else { wait = window.setTimeout((function (e) { return function () { event.click(d); wait = null; }; })(d3.event), 250); } } }); } return d3.rebind(cc, event, 'on'); } return { delayDblClick: delayDblClick }; }(); export default D3;
var temp = [{_id:""},{_id:"1"}]; //buildMap(temp); //function buildMap(input){ // d3.selectAll("svg").remove; var width = 960, height = 500, centered; var projection = d3.geo.albersUsa() .scale(1070) .translate([width / 2, height / 2]); var path = d3.geo.path() .projection(projection); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); svg.append("rect") .attr("class", "background") .attr("width", width) .attr("height", height) .on("click", clicked); var g = svg.append("g"); var div = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); //var totals = input; //if (!input) totals = "0"; d3.json("us.json", function(error, us) { if (error) throw error; g.append("g") .attr("id", "states") .selectAll("path") .data(topojson.feature(us, us.objects.states).features) .enter().append("path") .attr("id", function(d) {return d.id;}) /*.attr("value", function(d){ var result = 0; totals.forEach(function(D){ if (D._id === d.id){ result = D.total; } }) return result; })*/ .attr("d", path) .on("click", clicked) .on("mouseover", function(d) { //move the tooltip div and set the values when mousing over a bubble div.transition() .duration(200) .style("opacity", .9); div.html(d.id + "<br/>" + "$" + parseFloat(this.getAttribute("value")).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px"); }) .on("mouseout", function(d) { //hide the tooltip on mouseout div.transition() .duration(500) .style("opacity", 0); }); g.append("path") .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; })) .attr("id", "state-borders") .attr("d", path); }); function clicked(d) { var x, y, k; if (d && centered !== d) { var centroid = path.centroid(d); x = centroid[0]; y = centroid[1]; k = 4; centered = d; } else { x = width / 2; y = height / 2; k = 1; centered = null; } g.selectAll("path") .classed("active", centered && function(d) { return d === centered; }); g.transition() .duration(750) .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")") .style("stroke-width", 1.5 / k + "px"); } function colorStates(totals) { var result = 0; totals.forEach(function (D) { d3.selectAll("path#" + D._id) .style("fill", function (d) { var color = "#aaa"; if (D._id === d.id) { result = D.total; } if (result <= Math.pow(10,7)){ color = "#0F0"; }else if (result <= Math.pow(10,8)){ color = "#dcff00"; }else if (result <= Math.pow(10,8) * 5){ color = "#ffb700"; }else if (result <= Math.pow(10,9)){ color = "#ff9300"; }else if (result <= Math.pow(10,9)*5){ color = "#ff1a00"; } return color; }) .attr("value",result); }) }
export default { SEARCH_PRODUCT_IN_CATALOG: (state, value) => { state.searchValue = value; }, SWITH_MOBILE: (state) => { state.isMobile = true; state.isDesktop = false; }, SWITH_DESKTOP: (state) => { state.isDesktop = true; state.isMobile = false; }, SET_PRODUCTS_TO_STATE: (state, products) => { state.products = products; }, SET_CART: (state, product) => { if (state.cart.length) { let isProductExist = false state.cart.map(function (item) { if (item.article === product.article) { isProductExist = true item.quantity++ } }) isProductExist || state.cart.push({ ...product, quantity: 1 }) /* * в данной строке мы сразу ставим quantity:1 для любого нового товара в корзине, * компоненты получают его сразу в пропсах */ } else { state.cart.push({ ...product, quantity: 1 }); } }, REMOVE_FROM_CART: (state, index) => { state.cart.splice(index, 1) }, INCREASE_QUANTITY_IN_CART: (state, index) => { // if (state.products[index].quantity) { state.cart[index].quantity++; // state.products[index].quantity--; // } }, DECREASE_QUANTITY_IN_CART: (state, index) => { if (state.cart[index].quantity) { state.cart[index].quantity--; // state.products[index].quantity++; } }, }
"use strict"; var React = require('react'); var Input = React.createClass({ propTypes: { name: React.PropTypes.string.isRequired, label: React.PropTypes.string.isRequired, onChange: React.PropTypes.func.isRequired, placeholder: React.PropTypes.string, value: React.PropTypes.string, error: React.PropTypes.string }, render: function () { var wrapperClass = 'form-group'; if (this.props.error && this.props.error.length > 0){ wrapperClass += " " + 'has-error'; } return ( <div className={wrapperClass}> <label htmlFor={this.props.name}>{this.props.label}</label> <div className="field"> <input type="text" name={this.props.name} className="form-control" placeholder={this.props.placeholder} ref={this.props.name} value={this.props.value} onChange={this.props.onChange}/> <div className="input">{this.props.error}</div> </div> </div> ); } }); module.exports = Input;
import {createStore, combineReducers, applyMiddleware, compose} from 'redux'; import thunk from 'redux-thunk'; import expensesReducer from '../reducers/expenses'; import filtersReducer from '../reducers/filters'; import authReducer from '../reducers/auth'; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; export default () => { const store = createStore( combineReducers({ expenses: expensesReducer, filters: filtersReducer, auth: authReducer }), composeEnhancers(applyMiddleware(thunk)) ); return store; };
import { Colors, Metrics, Fonts } from '../../Themes/' export default { container: { position: 'absolute', top: 0, left: 0, right: 0, height: Metrics.navBarHeight, paddingTop: Metrics.smallMargin, paddingHorizontal: 5, backgroundColor: Colors.igniteBackground, flexDirection: 'row', justifyContent: 'space-between' }, title: { flex: 1, textAlign: 'center', color: Colors.snow, marginTop: Metrics.doubleBaseMargin, backgroundColor: Colors.transparent, fontWeight: 'bold', fontSize: Fonts.size.input }, logo: { alignSelf: 'center', marginTop: Metrics.baseMargin, height: Metrics.icons.large, width: Metrics.icons.large }, rightButtons: { flex: 1, justifyContent: 'flex-end', flexDirection: 'row' }, leftButtons: { flex: 1, justifyContent: 'flex-start', flexDirection: 'row' } }
import * as React from 'react'; import Box from '@mui/material/Box'; import Paper from '@mui/material/Paper'; export default function Card() { return ( <Paper elevation={3} > </Paper> ); }
"use strict"; var _babelHelpers = require("./utils/babelHelpers.js"); exports.__esModule = true; var _react = _babelHelpers.interopRequireDefault(require("react")); var _Icon = require("./Icon"); var _fragments = require("./fragments"); var OutlineCake = /*#__PURE__*/ function OutlineCake(props) { return _react.default.createElement(_Icon.Icon, props, _react.default.createElement("path", { d: _fragments.jh })); }; exports.OutlineCake = OutlineCake;
!function(v){var c,a='<svg><symbol id="icon-diaoping" viewBox="0 0 1024 1024"><path d="M810.16 95.456 517.936 95.456c-3.968-17.296-10.48-33.904-21.44-46.016-11.552-12.768-26.688-19.52-43.776-19.52-22.192 0-40.864 8.48-54 24.528-9.44 11.552-15.024 26-18.176 40.992l-82.384 0c-13.248 0-24 10.752-24 24 0 13.248 10.752 24 24 24l79.168 0c0.336 7.632 0.944 14.704 1.648 20.48-79.104 0.768-143.024 65.056-143.024 144.368l0 407.584c0 79.744 64.656 144.4 144.4 144.4l21.264 0 0 44.128c0 5.344 3.952 11.344 8.848 13.488l29.264 12.752c4.896 2.128 12.864 2.336 17.872 0.48l33.664-12.528c4.992-1.824 9.024-7.68 9.024-13.008l0-45.312 21.28 0c79.728 0 144.384-64.656 144.384-144.384L665.952 308.304c0-79.264-63.856-143.536-142.928-144.352 0.304-5.744 0.352-12.864 0.272-20.496l262.832 0 0 777.088c0 13.232 10.752 24 24 24s24-10.768 24-24L834.128 119.456C834.16 106.208 823.408 95.456 810.16 95.456zM435.872 84.864c2.8-3.44 7.008-6.944 16.848-6.944 3.504 0 5.728 0.992 8.16 3.712 2.992 3.296 5.408 8.128 7.376 13.824l-37.92 0C431.808 91.408 433.552 87.696 435.872 84.864zM475.216 143.456c0.16 7.056 0.096 14.016-0.24 20.416l-47.568 0c-0.88-5.872-1.632-12.944-2.032-20.416L475.216 143.456zM279.488 366.416c-8.848 0-16-7.152-16-16 0-88.432 71.968-160.384 160.416-160.384 8.848 0 16 7.152 16 16 0 8.848-7.152 16-16 16-70.816 0-128.416 57.6-128.416 128.384C295.488 359.264 288.32 366.416 279.488 366.416zM607.424 491.632l0 197.328c0 62.976-47.04 114-105.088 114l-102.72 0c-58.048 0-105.088-51.024-105.088-114L294.528 491.632 607.424 491.632z" ></path></symbol><symbol id="icon-shoujitubiao" viewBox="0 0 1024 1024"><path d="M755.231506 0.220952l-486.455013 0c-77.567259 0-140.681638 60.963843-140.681638 135.85168l0 752.091683c0 74.888837 63.113379 135.834684 140.681638 135.834684l486.455013 0c77.576257 0 140.67264-60.946846 140.67264-135.834684L895.904146 136.072633C895.904146 61.184795 832.807763 0.220952 755.231506 0.220952zM512.016996 960.450715c-35.2134 0-63.84722-28.608826-63.84722-63.813228 0-35.178408 28.63482-63.80523 63.84722-63.80523 35.187406 0 63.822226 28.625822 63.822226 63.80523C575.839222 931.84189 547.204402 960.450715 512.016996 960.450715zM831.928953 768.063236 192.088043 768.063236 192.088043 192.189522l639.840909 0L831.928953 768.063236z" ></path></symbol><symbol id="icon-shouquan" viewBox="0 0 1024 1024"><path d="M512 42.666667 128 213.333333l0 256c0 236.8 163.84 458.24 384 512 220.16-53.76 384-275.2 384-512L896 213.333333 512 42.666667zM426.666667 725.333333l-170.666667-170.666667 60.16-60.16L426.666667 604.586667l281.173333-281.173333L768 384 426.666667 725.333333z" ></path></symbol><symbol id="icon-yiyao" viewBox="0 0 1024 1024"><path d="M 408.503 614.675 c -12.897 12.897 -19.997 30.039 -19.997 48.277 c 0 18.239 7.1 35.381 19.997 48.278 c 12.903 12.903 30.041 20.003 48.277 20.003 c 18.243 0 35.394 -7.1 48.292 -20.003 l 101.314 -101.315 l -96.562 -96.567 l -101.322 101.327 Z" ></path><path d="M 457.244 371.15 c -1.262 -4.724 -6.155 -7.562 -10.878 -6.294 l -153.447 40.918 c -4.716 1.262 -7.556 6.155 -6.294 10.878 c 1.255 4.725 6.146 7.555 10.871 6.294 l 153.454 -40.925 c 4.724 -1.257 7.55 -6.156 6.294 -10.871 Z" ></path><path d="M 509.671 3.093 c -280.905 0 -508.62 227.715 -508.62 508.62 c 0 280.899 227.715 508.62 508.62 508.62 c 280.899 0 508.62 -227.721 508.62 -508.62 c 0 -280.905 -227.721 -508.62 -508.62 -508.62 Z M 261.386 393.9 c 0 -61.054 49.491 -110.553 110.545 -110.553 c 61.062 0 110.554 49.498 110.554 110.553 s -49.491 110.545 -110.554 110.545 c -61.055 0 -110.545 -49.491 -110.545 -110.545 Z M 725.835 526.711 l -202.644 202.646 c -17.738 17.738 -41.317 27.51 -66.41 27.51 c -25.085 0 -48.67 -9.773 -66.403 -27.51 c -17.732 -17.74 -27.51 -41.318 -27.51 -66.404 c 0 -25.085 9.777 -48.671 27.51 -66.41 l 202.651 -202.643 c 17.733 -17.739 41.317 -27.51 66.41 -27.51 c 25.077 0 48.671 9.773 66.396 27.51 c 17.739 17.739 27.51 41.318 27.51 66.403 c 0.001 25.091 -9.77 48.677 -27.509 66.409 Z" ></path></symbol><symbol id="icon-icon145" viewBox="0 0 1024 1024"><path d="M929.9643 266.596847c-33.913391-33.943067-79.049381-52.639894-127.036301-52.639894-48.021713 0-93.143377 18.697851-127.07007 52.639894L288.113907 654.325519c-33.92874 33.948183-52.645011 79.063707-52.645011 127.055744 0 48.00227 18.717294 93.123934 52.645011 127.050628 33.926694 33.943067 79.062684 52.643987 127.050628 52.643987 48.007387 0 93.123934-18.700921 127.07007-52.643987l387.730719-387.728672c33.94102-33.913391 52.623521-79.048357 52.623521-127.055744C982.603171 345.645205 963.921693 300.537867 929.9643 266.596847M507.570107 873.756137c-24.668843 24.684192-57.495482 38.279838-92.405573 38.279838-34.895765 0-67.687612-13.57518-92.375897-38.279838-24.668843-24.671912-38.264489-57.464783-38.264489-92.373851 0-34.895765 13.576203-67.692728 38.264489-92.359524l193.871499-193.886849 184.750771 184.779424L507.570107 873.756137 507.570107 873.756137zM507.570107 873.756137" ></path><path d="M252.817006 55.075363c-116.814496 0-211.506135 94.712105-211.506135 211.521484 0 116.813472 94.691639 211.520461 211.506135 211.520461 116.828822 0 211.535811-94.691639 211.535811-211.520461C464.352817 149.765979 369.661178 55.075363 252.817006 55.075363M404.02073 243.862054l-293.617248 78.295204c-9.046027 2.419096-18.403139-3.00238-20.804838-12.043291-2.419096-9.039887 3.01773-18.395976 12.043291-20.815071L395.245879 211.019041c9.039887-2.438539 18.402115 3.003404 20.819165 12.043291C418.446277 232.082776 413.060617 241.460354 404.02073 243.862054" ></path></symbol><symbol id="icon-icon22501" viewBox="0 0 1024 1024"><path d="M740.770334 322.323033 278.289144 322.323033c-36.396955 0-66.00325 29.302373-66.00325 65.323774l0 501.713726c0 36.023448 29.607318 65.329914 66.00325 65.329914l462.48119 0c36.389792 0 65.99711-29.30749 65.99711-65.329914L806.767444 387.646807C806.767444 351.625406 777.160125 322.323033 740.770334 322.323033L740.770334 322.323033zM754.50515 889.35951c0 7.207146-6.160303 13.06762-13.734816 13.06762L278.289144 902.42713c-7.574512 0-13.741979-5.860475-13.741979-13.06762L264.547165 387.646807c0-7.201006 6.166443-13.06148 13.741979-13.06148l462.48119 0c7.574512 0 13.734816 5.860475 13.734816 13.06148L754.50515 889.35951 754.50515 889.35951zM754.50515 889.35951" ></path><path d="M746.013755 70.155826 273.046746 70.155826c-36.023448 0-65.329914 29.308513-65.329914 65.329914l0 86.22685c0 36.023448 29.30749 65.329914 65.329914 65.329914l472.967008 0c36.023448 0 65.329914-29.30749 65.329914-65.329914l0-86.22685C811.343669 99.465362 782.036179 70.155826 746.013755 70.155826L746.013755 70.155826zM759.081375 221.712591c0 7.207146-5.860475 13.06762-13.06762 13.06762L273.046746 234.780211c-7.207146 0-13.06762-5.860475-13.06762-13.06762l0-86.22685c0-7.207146 5.860475-13.06762 13.06762-13.06762l472.967008 0c7.207146 0 13.06762 5.860475 13.06762 13.06762L759.081375 221.712591 759.081375 221.712591zM759.081375 221.712591" ></path><path d="M568.32175 466.043319 450.737728 466.043319l0 99.29447-99.30061 0 0 117.592208 99.30061 0 0 99.29447 117.584022 0 0-99.29447 99.30061 0L667.62236 565.337789l-99.30061 0L568.32175 466.043319 568.32175 466.043319zM628.426663 604.533486l0 39.200814-99.299587 0 0 99.29447L489.932402 743.02877 489.932402 643.7343 390.630768 643.7343l0-39.200814 99.30061 0 0-99.29447 39.195697 0 0 99.29447L628.426663 604.533486 628.426663 604.533486zM628.426663 604.533486" ></path></symbol><symbol id="icon-diqiu" viewBox="0 0 1024 1024"><path d="M494.913264 0l34.034995 0c59.032926 2.745437 117.855127 14.178739 172.733772 36.419191 114.435372 45.281656 211.019379 133.581185 266.608467 243.356538 35.335466 68.792474 54.05381 145.755033 55.703481 223.018627l0 18.345061c-1.631609 76.264158-19.832173 152.21524-54.318721 220.339417-33.583443 67.100659-82.296896 126.512888-141.239511 172.938476-60.297272 47.557479-131.45588 81.29746-206.509878 97.637629-30.482785 6.875635-61.645908 10.078645-92.784948 11.93904L495.081844 1023.993979c-40.82032-2.16143-81.55635-7.658325-120.925682-18.880903-95.319661-26.424835-182.354845-81.484102-247.35428-155.996237-45.721167-52.018815-80.617121-113.520226-101.960489-179.416745C9.223706 621.775353 1.258325 571.520602 0 521.1635l0-18.308937C1.824271 409.371214 29.32079 316.507996 79.720038 237.679022c53.439699-84.217498 131.937535-152.353716 223.078833-192.975353C363.102164 17.279398 428.854186 2.986265 494.913264 0L494.913264 0 494.913264 0zM397.179304 109.221449c-32.445532 40.760113-53.626341 89.08222-70.815428 137.916087 24.136971 6.062841 48.918156 8.699906 73.476576 12.402634 30.458702 3.142803 60.995673 5.918344 91.659078 6.153151C491.469426 191.434055 491.517592 117.18683 491.469426 42.89746 452.49746 51.11571 421.153716 78.696519 397.179304 109.221449L397.179304 109.221449 397.179304 109.221449zM532.49445 265.681279c41.440452-0.746566 82.862841-4.184384 123.803575-10.825212 13.92587-1.770085 27.719285-4.383067 41.3381-7.760677-20.121167-57.160489-46.040263-114.07413-88.55842-158.235936-20.783443-21.782879-46.696519-39.640263-76.523048-45.961994C532.446284 117.162747 532.542615 191.422013 532.49445 265.681279L532.49445 265.681279 532.49445 265.681279zM356.726246 67.263217c-72.404892 25.232738-138.445908 68.533584-190.422578 124.911383 38.020696 20.085042 78.756726 34.932079 120.353716 45.588711 21.722672-65.481091 52.199436-130.239699 101.304233-179.784008C377.274882 60.080527 367.015616 63.801317 356.726246 67.263217L356.726246 67.263217 356.726246 67.263217zM635.833678 57.678269c10.217121 9.42841 18.441392 20.681091 27.364064 31.259454 33.457008 44.703669 56.859454 96.096331 74.241204 148.939981 41.572907-10.843274 82.194544-25.756538 120.377799-45.570649C798.380433 127.879586 720.617121 80.237817 635.833678 57.678269L635.833678 57.678269 635.833678 57.678269zM138.993791 224.198683C80.153528 300.577234 45.239511 395.132267 41.494638 491.559737c68.244591-0.120414 136.489182-0.042145 204.71571-0.042145 1.318532-72.242333 10.590405-144.400376 28.760865-214.360865C227.829163 264.760113 181.819003 247.552963 138.993791 224.198683L138.993791 224.198683 138.993791 224.198683zM749.010724 277.156726c18.188523 69.960489 27.442333 142.118532 28.742803 214.342803 68.280715-0.018062 136.555409 0 204.830103 0-4.009784-96.403387-38.676952-191.018627-97.685795-267.342992C842.199059 247.673377 796.074506 264.64572 749.010724 277.156726L749.010724 277.156726 749.010724 277.156726zM287.13302 491.33095c68.130198 0.361242 136.248354 0.066228 204.360489 0.162559L491.493509 306.640075c-59.297836-1.101787-118.637817-7.26096-176.611101-19.958608C297.259831 353.420884 288.656256 422.375917 287.13302 491.33095L287.13302 491.33095 287.13302 491.33095zM532.49445 306.622013c0 61.639887 0 123.255691 0.024083 184.877516 68.118156-0.126435 136.236312 0.222766 204.354468-0.180621-1.541298-68.961054-10.144873-137.922107-27.755409-204.679586C651.15635 299.41524 591.798307 305.520226 532.49445 306.622013L532.49445 306.622013 532.49445 306.622013zM41.464534 532.470367c3.835183 96.427469 38.682973 190.982502 97.55936 267.361054 42.771025-23.420508 88.853434-40.513264 135.95936-53.000188-18.194544-69.954468-27.382126-142.130574-28.809031-214.360865C177.941675 532.512512 109.697084 532.512512 41.464534 532.470367L41.464534 532.470367 41.464534 532.470367zM287.163123 532.638946c1.517215 68.973095 10.018438 138.024459 27.809595 204.757855 57.907056-12.920414 117.265099-18.880903 176.496707-20.018815 0.024083-61.615804 0.024083-123.261712 0.024083-184.871496C423.381373 532.596802 355.263217 532.313829 287.163123 532.638946L287.163123 532.638946 287.163123 532.638946zM532.49445 532.50047l0 184.853434c59.339981 1.083725 118.679962 7.321167 176.677328 19.940546 17.369708-66.85381 26.545249-135.844967 27.454374-204.902352C668.580245 532.638946 600.540357 532.446284 532.49445 532.50047L532.49445 532.50047 532.49445 532.50047zM777.741486 532.50047c-1.198119 72.21223-10.584384 144.370273-28.706679 214.336783 47.075823 12.420696 93.14619 29.513452 135.905174 52.982126 58.990781-76.300282 93.639887-170.921543 97.649671-267.294826C914.308937 532.470367 846.016181 532.512512 777.741486 532.50047L777.741486 532.50047 777.741486 532.50047zM326.4 776.760113c19.940546 57.298965 46.052305 114.260771 88.600564 158.452681 20.75334 21.740734 46.672437 39.580056 76.474882 45.847601 0.066228-74.223142 0-148.476388 0.024083-222.741675C436.073001 759.414487 380.616369 765.0619 326.4 776.760113L326.4 776.760113 326.4 776.760113zM532.49445 758.294638c0.024083 74.253246-0.042145 148.542615 0.048166 222.78984 38.893697-8.21223 70.213358-35.696707 94.151646-66.173471 32.505738-40.814299 53.812982-89.196613 70.91778-138.150894-24.853434-6.002634-50.278833-8.898589-75.535654-12.565193C592.279962 761.292944 562.453434 758.481279 532.49445 758.294638L532.49445 758.294638 532.49445 758.294638zM166.219379 831.711007c59.41825 64.379304 137.139417 112.081279 221.892756 134.544497-49.098777-49.658702-79.756162-114.41731-101.442709-180.030856C244.976105 796.730762 204.438758 812.005268 166.219379 831.711007L166.219379 831.711007 166.219379 831.711007zM737.402822 786.176482c-21.825024 65.655691-52.422201 130.498589-101.629351 180.217498 84.705174-22.65588 162.480527-70.171214 221.92286-134.5746C819.71778 811.698213 778.957667 796.965569 737.402822 786.176482L737.402822 786.176482 737.402822 786.176482zM737.402822 786.176482" fill="" ></path></symbol><symbol id="icon-jiankangfuwu" viewBox="0 0 1042 1024"><path d="M520.863544 933.800407c-48.488798-38.0611-99.063136-73.515275-167.885947-117.311609-89.678208-56.830957-174.142566-111.05499-249.743381-210.639511-52.138493-68.822811-80.814664-149.11609-80.814664-225.759674 0-77.164969 28.676171-146.509165 82.900204-200.733198 57.352342-57.352342 133.474542-88.635438 214.81059-88.635437 72.99389 0 143.380855 26.069246 198.647658 72.99389l1.564155 1.564154 1.564155-1.564154c55.266802-46.924644 125.653768-72.99389 198.647657-72.99389 80.814664 0 156.936864 31.283096 214.289206 88.635437 55.266802 55.266802 85.507128 128.260692 84.985744 206.468432 0 79.250509-29.718941 157.458248-84.464359 221.06721-71.429735 83.421589-145.98778 132.431772-225.238289 184.570265-68.822811 45.360489-127.217923 87.071283-189.262729 142.338085zM319.608961 132.431772c-69.86558 0-135.560081 27.112016-184.570264 76.122199-45.881874 46.403259-70.386965 105.319756-70.386966 171.535642 0 67.780041 25.547862 139.209776 71.95112 200.211813 70.386965 92.806517 151.201629 144.423625 237.230143 199.690427l1.564155 1.04277c42.753564 27.112016 91.763747 58.395112 141.8167 96.977597l1.564155 1.04277 1.564155-1.564155c57.352342-49.010183 112.619145-85.507128 166.321792-120.961303l2.08554-1.564155c76.1222-50.052953 147.551935-97.498982 214.289206-175.706721 47.446029-55.266802 74.03666-124.089613 74.036659-193.955194 0-68.301426-25.026477-129.303462-72.472505-177.270875-49.531568-49.010183-115.226069-76.1222-185.091649-76.1222-89.156823 0-144.94501 36.496945-200.211813 91.242362-54.224033-54.224033-110.01222-90.720978-199.690428-90.720977z m135.560082 669.979633c-11.470468-0.521385-20.855397-10.427699-20.334012-21.898167 1.04277-37.539715 5.735234-71.95112 13.034623-103.755601 8.342159-33.89002 20.334012-65.173116 35.454175-93.327902 3.649695-6.778004 10.949084-10.949084 18.769857-10.949083 3.649695 0 6.778004 1.04277 9.906314 2.606924 9.906314 5.735234 14.077393 18.248473 8.342159 28.676171-14.077393 26.069246-24.505092 53.702648-31.804481 83.421589-7.299389 29.197556-10.949084 61.523422-11.991853 94.892057 0 11.470468-9.384929 20.334012-21.376782 20.334012z m120.439918-231.494908c-13.556008 0-26.069246-1.564155-42.232179-3.649695-2.08554-21.898167-3.12831-40.14664-0.521385-61.523421 6.256619-49.531568 29.718941-96.977597 66.215886-133.474542 37.01833-37.01833 84.464358-59.959267 133.995927-64.130346 5.735234-0.521385 11.991853-1.04277 17.727087-1.04277 13.034623 0 25.547862 1.564155 40.668025 3.12831 3.12831 21.898167 5.213849 39.625255 2.08554 62.566191-6.256619 45.881874-29.197556 91.242363-65.173117 128.260692-36.496945 37.539715-82.378819 62.044807-129.303462 68.301426-8.342159 1.04277-16.162933 1.564155-23.462322 1.564155z m174.663951-221.588595c-44.317719 0-87.592668 18.769857-121.482688 52.659878s-53.702648 79.250509-54.745417 124.089613v2.606925h2.606924c42.753564-0.521385 87.071283-21.376782 122.004073-57.352342 33.368635-34.411405 53.702648-78.207739 54.745418-119.918534v-2.606925h-3.12831z m-322.73727 214.289206c-31.283096 0-63.087576-8.863544-92.285133-25.547862-34.93279-19.812627-64.130346-50.574338-79.250509-84.464358-7.820774-17.727088-9.906314-32.325866-13.034623-51.095723v-1.04277l2.606924-1.04277c15.641548-6.778004 28.676171-11.991853 45.360489-15.641548 10.427699-2.08554 21.376782-3.12831 31.804481-3.128309 29.718941 0 59.437882 7.820774 86.549898 22.419552 36.496945 20.334012 65.694501 51.617108 81.336049 88.635438 7.820774 17.727088 10.427699 33.89002 13.556008 51.095723l-4.171079 1.564154c-16.684318 6.778004-30.761711 13.034623-49.531569 16.162933-7.299389 1.564155-15.120163 2.08554-22.940936 2.08554z m-103.234216-139.731161c-9.906314 0-19.812627 1.04277-29.718941 3.12831l-3.12831 0.521385 1.04277 3.128309c11.991853 29.718941 33.368635 53.702648 63.608961 70.90835 23.462322 13.034623 46.403259 19.812627 69.865581 19.812628 8.342159 0 17.205703-1.04277 25.547861-2.606925l3.12831-0.521385-1.04277-3.128309c-13.034623-32.325866-34.93279-57.352342-65.173116-74.03666-19.812627-11.470468-41.710794-17.205703-64.130346-17.205703z" ></path></symbol><symbol id="icon-tou" viewBox="0 0 1024 1024"><path d="M133.11488 433.34144V253.12256S255.40608 2.5088 541.81888 2.5088C828.24192 2.5088 980.48 271.36 980.48 476.23168c0 127.92832-189.6704 246.58944-174.08 302.86336C915.62496 993.28 934.44096 1024 934.44096 1024h-38.62016s-133.82144-210.53952-133.82144-262.03136 147.05152-141.2608 179.23072-276.42368c24.6016-103.31136-112.98816-451.25632-392.97024-448.04096-279.98208 3.21536-370.08896 222.0544-370.08896 222.0544v202.74688S63.5392 588.84096 83.2 597.76c42.31168 19.2-8.0384 4.0704 55.04 23.04l30.27456 122.56256 43.34592 6.18496-1.50528 34.57024-38.37952 8.27392 9.41568 40.00256s3.21536 32.1792 41.83552 32.1792c38.61504 0 173.77792 3.22048 173.77792 3.22048L491.93984 1024h-46.66368l-77.2352-120.8064-151.25504 3.21536s-61.14304-22.52288-77.2352-70.79936c-16.09216-48.27136-48.95232-202.74176-48.95232-202.74176L20.48 626.432l112.63488-193.09056z" ></path><path d="M217.87136 434.39616h123.35616v41.83552H217.87136zM577.21856 512.91136s64.36352-93.82912 99.7632 4.85376c19.07712 53.1712 21.98528 74.99776-4.98688 95.35488-23.08096 17.42336-35.84 47.36-35.84 47.36l-77.13792 5.5296s-29.75744 35.72224 10.15296 42.15296c24.1408 3.89632 171.10528-5.90848 187.19744-179.69152-11.80672-155.55072-130.87744-112.66048-153.40544-94.40768-22.52288 18.2528-38.00064 68.992-38.00064 68.992l12.25728 9.856z" ></path></symbol><symbol id="icon-zhensuo" viewBox="0 0 1024 1024"><path d="M512 25.6c268.20096 0 486.4 218.19904 486.4 486.4s-218.19904 486.4-486.4 486.4-486.4-218.19904-486.4-486.4S243.79904 25.6 512 25.6m0-25.6C229.22752 0 0 229.22752 0 512s229.22752 512 512 512 512-229.22752 512-512S794.77248 0 512 0z" fill="#5B271F" ></path><path d="M763.15648 751.65184V496.68096c0.04096-0.39936 0.0768-0.77824 0.0768-1.14176 0-3.33312-1.76128-6.36416-4.7872-8.56064L509.5168 308.43904 259.56864 487.72096c-2.45248 2.02752-3.72224 4.608-3.81952 7.45984h-0.02048v256.47104c0 27.008 21.9136 48.9216 48.95232 48.9216h409.59488c27.02336-0.00512 48.88064-21.9136 48.88064-48.9216z m-76.5952 8.24832H332.39552c-22.25664 0-30.48448-8.2176-30.48448-30.46912V501.41696l207.60576-148.8384 207.46752 148.80256v228.04992c-0.01024 22.25152-8.17152 30.46912-30.42304 30.46912z" fill="#5B271F" ></path><path d="M785.94048 465.42848c10.86464 0 19.76832-16.10752 19.76832-23.92064 0-3.92192-2.03264-7.49568-5.6064-10.05056L509.5168 213.30944 217.76896 432.32768c-3.04128 2.49856-4.51584 5.64224-4.51584 9.18016 0 7.81312 8.832 23.92064 19.69152 23.92064 4.98688 0 9.2928-1.1776 12.73344-3.3024l263.8336-198.9888 263.14752 198.46144c3.52256 2.32448 8.0896 3.82976 13.28128 3.82976z" fill="#5B271F" ></path><path d="M512 0c282.76736 0 511.99488 229.22752 511.99488 512S794.76736 1024 512 1024c282.77248 0 512-229.22752 512-512S794.77248 0 512 0z" fill="#5B271F" ></path><path d="M619.48416 572.032h-92.8512V479.20128a17.19296 17.19296 0 0 0-17.19296-17.19808 17.24416 17.24416 0 0 0-17.19296 17.19808v92.83072H399.40608a17.2544 17.2544 0 0 0-17.19296 17.19808 17.22368 17.22368 0 0 0 17.19296 17.18784h92.84096v92.8512a17.23392 17.23392 0 0 0 17.19296 17.19808 17.18272 17.18272 0 0 0 17.19296-17.19808v-92.8512h92.8512a17.16736 17.16736 0 0 0 17.1776-17.18784 17.18784 17.18784 0 0 0-17.1776-17.19808z" fill="#5B271F" ></path></symbol><symbol id="icon-icon-test" viewBox="0 0 1024 1024"><path d="M137 474.4c0 227.4 168.2 412.4 375 412.4S887 702 887 474.4v-37.4h-750v37.4zM876 201c14.6-14.6 14.6-38.4 0-53-14.6-14.6-38.4-14.6-53 0l-198.4 214h112.4l139-161z" ></path></symbol><symbol id="icon-qingdan" viewBox="0 0 1024 1024"><path d="M814.004 64.021H209.408c-80.317 0-145.426 65.11-145.426 145.426v604.596c0 80.317 65.11 145.426 145.426 145.426h604.596c80.318 0 145.426-65.11 145.426-145.426V209.447c0-80.316-65.11-145.426-145.426-145.426z m-17.34 828.91H226.748c-54.57 0-98.806-44.237-98.806-98.805V226.14c0-54.57 44.237-98.806 98.806-98.806h569.914c54.57 0 98.807 44.238 98.807 98.806v567.983c0 54.57-44.238 98.808-98.807 98.808z" fill="#E0620D" ></path><path d="M255.863 255.903h63.961v63.961h-63.96v-63.96zM383.785 255.903h383.764v63.961H383.785v-63.96zM255.863 703.627h63.961v63.961h-63.96v-63.96zM383.785 703.627h383.764v63.961H383.785v-63.96zM255.863 479.765h63.961v63.96h-63.96v-63.96zM383.785 479.765h383.764v63.96H383.785v-63.96z" fill="#E0620D" ></path></symbol><symbol id="icon-shiguan" viewBox="0 0 1024 1024"><path d="M458.5 64.4H148.1c-16.4 0-29.7 13.3-29.7 29.7s13.3 29.7 29.7 29.7h12.1v692.5c0 78.9 64.2 143.2 143.2 143.2s143.2-64.2 143.2-143.2V123.9h12.1c16.4 0 29.7-13.3 29.7-29.7-0.1-16.5-13.4-29.8-29.9-29.8z m-71.5 752c0 46.2-37.5 83.7-83.7 83.7-38.9 0-71.3-26.7-80.7-62.7 6.6 1.7 13.4 2.9 20.6 2.9 45.8 0 83-37.2 83-83.1v-76.8H387v136z m0-195.5H266.8v136.3c0 13-10.5 23.6-23.5 23.6s-23.6-10.6-23.6-23.6V124.8H387v496.1zM875.9 64.4H565.5c-16.4 0-29.7 13.3-29.7 29.7s13.3 29.7 29.7 29.7h12.1v692.5c0 78.9 64.2 143.2 143.2 143.2S864 895.3 864 816.3V123.9h12.1c16.4 0 29.7-13.3 29.7-29.7-0.1-16.5-13.4-29.8-29.9-29.8z m-71.5 752c0 46.2-37.5 83.7-83.7 83.7-38.9 0-71.3-26.7-80.7-62.7 6.6 1.7 13.5 2.9 20.6 2.9 45.8 0 83.1-37.2 83.1-83.1V335.5h60.7v480.9z m0-540.4H684.2v481.2c0 13-10.6 23.6-23.6 23.6-13 0-23.5-10.6-23.5-23.6l-0.1-632.4h167.3V276z" fill="" ></path></symbol><symbol id="icon-yinxingyanjing" viewBox="0 0 1024 1024"><path d="M516.47488 79.49312c-244.864 0-443.3664 198.47168-443.3664 443.29472 0 244.83328 198.5024 443.30496 443.3664 443.30496 244.86912 0 443.37152-198.47168 443.37152-443.30496 0.00512-244.82816-198.5024-443.29472-443.37152-443.29472z m362.9312 652.84096v0.01536c-27.67872 47.9232-124.36992 47.29344-238.80704 5.61152-21.12 119.77728-68.91008 203.68384-124.25216 203.67872h-0.01536c-55.36768 0.01536-103.16288-83.97824-124.27776-203.84256-114.37056 41.60512-210.9952 42.20928-238.6688-5.6832v-0.01024c-27.68896-47.9232 21.20192-131.2768 114.5344-209.47968-93.24032-78.16192-142.06464-161.46432-114.3808-209.36704v-0.02048c27.68896-47.91808 124.37504-47.2832 238.81728-5.61664 21.12512-119.77216 68.9152-203.6736 124.24704-203.66848l0.01024-0.01024c55.38304 0 103.18336 83.9936 124.288 203.85792 114.37056-41.60512 210.98496-42.2144 238.65856 5.67808l0.01024 0.01536c27.68896 47.9232-21.21216 131.2768-114.54464 209.47456 93.24544 78.16704 142.06464 161.46944 114.3808 209.36704z" fill="#E46588" ></path></symbol><symbol id="icon-kefu" viewBox="0 0 1117 1024"><path d="M1047.272727 414.254545C1005.381818 174.545455 802.909091 0 558.545455 0S111.709091 181.527273 69.818182 414.254545c-41.890909 34.909091-69.818182 97.745455-69.818182 160.581819 0 83.781818 48.872727 181.527273 125.672727 181.527272 69.818182 0 69.818182-76.8 69.818182-181.527272 0-97.745455 0-174.545455-48.872727-181.527273C188.509091 202.472727 356.072727 62.836364 558.545455 62.836364s370.036364 139.636364 411.927272 323.490909c-48.872727 13.963636-48.872727 83.781818-48.872727 181.527272 0 69.818182 0 118.690909 13.963636 153.6-62.836364 97.745455-153.6 167.563636-265.309091 195.49091-20.945455-27.927273-62.836364-48.872727-111.70909-48.872728-69.818182 0-125.672727 34.909091-125.672728 76.8S488.727273 1024 558.545455 1024c69.818182 0 125.672727-34.909091 125.672727-76.8 111.709091-27.927273 209.454545-104.727273 272.290909-202.472727 6.981818 6.981818 20.945455 6.981818 34.909091 6.981818 76.8 0 125.672727-97.745455 125.672727-181.527273 0-58.181818-27.927273-121.018182-69.818182-155.927273z" fill="#B88C4B" ></path></symbol><symbol id="icon-dagou" viewBox="0 0 1024 1024"><path d="M256.836553 538.045189a5.505387 5.505387 0 0 0 0.476861 7.085372L425.709705 719.411887l0.034792 0.036839a5.505387 5.505387 0 0 0 7.785314 0.062421l363.934756-358.166379 0.055259-0.055258a5.505387 5.505387 0 0 0-0.048096-7.785314l-22.093181-21.818935a5.505387 5.505387 0 0 0-7.392364-0.312108L432.961876 610.475825a5.505387 5.505387 0 0 1-6.872525 0.140193L288.163025 504.903372l-0.089027-0.066515a5.505387 5.505387 0 0 0-7.696286 1.175778l-23.541159 32.032554z m767.138888-19.72525c0 276.441053-229.213425 505.654478-518.296403 505.654478-276.441053 0-505.654478-229.213425-505.654479-505.654478 0-289.082978 229.213425-518.296403 505.654479-518.296403 289.082978 0.001023 518.296403 229.214449 518.296403 518.296403z" fill="#09BB07" ></path></symbol><symbol id="icon-yisheng" viewBox="0 0 1024 1024"><path d="M806.848 863.68a434.24 434.24 0 0 0-307.392-255.616C581.696 551.36 637.44 429.696 637.44 285.12c0-92.032-23.424-179.328-65.984-245.824L566.336 31.36 557.44 28.16a495.104 495.104 0 0 0-326.336 0l-8.96 3.2-5.12 7.872C174.464 105.792 151.04 193.088 151.04 285.056c0 148.48 58.688 272.96 144.512 327.616a435.264 435.264 0 0 0-287.744 251.008l-1.28 3.84c-5.248 20.736-14.144 72.96 14.72 111.232 11.456 15.104 33.536 33.664 73.856 36.416 37.12 2.432 141.696 4.928 312.32 7.36h1.408c169.088-2.432 273.664-4.928 310.848-7.36 40.32-2.752 62.336-21.312 73.728-36.48 28.928-38.208 19.968-90.432 14.848-111.104l-1.344-3.84m211.968-5.568c-44.288-134.336-141.76-185.088-206.272-218.624-10.24-5.376-19.84-10.304-28.288-15.232a430.4 430.4 0 0 0-34.176-16.896c-5.952-2.688-13.376-6.08-18.56-8.896 146.368-210.368 127.552-397.568 126.784-404.544-5.76-107.648-113.152-146.24-169.152-151.68L670.72 40.64l-3.648 35.712 18.432 1.792c5.312 0.512 130.176 13.696 135.872 118.72 0 0.832 3.648 39.808-5.76 100.8-42.432-16.448-106.24-20.288-114.944-20.736l-1.92 35.84c31.616 1.6 84.992 8.512 110.144 20.736-15.232 70.144-47.232 160.32-114.56 254.208l-2.112 3.712c-10.048 24.832 17.664 37.44 42.048 48.512 9.6 4.48 20.544 9.408 31.104 15.36 8.832 5.12 18.816 10.304 29.632 15.936 62.784 32.64 148.8 77.44 187.904 195.264 7.36 45.248 0.32 59.648-3.072 63.744-1.6 1.92-4.16 4.032-10.816 4.48-24.64 1.536-57.6 2.432-57.6 2.432l0.96 35.84s33.792-0.832 59.136-2.496a50.56 50.56 0 0 0 37.312-17.856c14.592-17.728 17.984-46.848 9.984-94.4M420.288 130.432v131.008H533.76c11.328 0 18.88 9.344 18.88 18.688a18.816 18.816 0 0 1-18.88 18.688H420.288v131.008a18.816 18.816 0 0 1-18.88 18.688c-9.472 0-18.88-9.344-18.88-18.688V298.816H269.056c-9.408 0-18.88-9.344-18.88-18.688s9.472-18.688 18.88-18.688h113.472V130.432c0-9.344 9.408-18.752 18.88-18.752 11.328 0 18.88 9.408 18.88 18.752z" ></path></symbol><symbol id="icon-tou1" viewBox="0 0 1024 1024"><path d="M787.34676 991.738385V728.949153c16.74337-34.711864 112.915653-228.485743 112.915653-361.411765v-17.968495a339.359521 339.359521 0 1 0-678.514856 0V367.537388L125.779462 580.300698a22.052243 22.052243 0 0 0 20.418743 31.03649h75.549352v113.119841a108.831904 108.831904 0 0 0 108.831905 108.831904h71.873978v158.653639a22.052243 22.052243 0 0 0 43.900299 0v-158.653639h24.502492a22.052243 22.052243 0 1 0 0-43.900299h-140.276769a64.931605 64.931605 0 0 1-64.727418-64.727418v-135.172083a22.052243 22.052243 0 0 0-22.052243-22.052244H179.889133l83.921036-185.606381a22.052243 22.052243 0 0 0 2.041875-8.984247v-23.277368a295.255035 295.255035 0 1 1 590.51007 0V367.537388c0 132.31346-109.852841 343.647458-111.077966 345.689332a21.848056 21.848056 0 0 0-2.45025 10.209372v268.302293a22.052243 22.052243 0 0 0 43.900299 0z" ></path><path d="M556.20658 301.584845a22.052243 22.052243 0 0 0 22.052244-22.052243V152.732203a22.052243 22.052243 0 1 0-43.9003 0v127.004587a22.052243 22.052243 0 0 0 21.848056 21.848055zM578.258824 399.594816a22.052243 22.052243 0 0 0-43.9003 0v127.004586a22.052243 22.052243 0 1 0 43.9003 0zM594.185444 339.563709a22.052243 22.052243 0 0 0 22.052243 22.052243h127.004586a22.052243 22.052243 0 1 0 0-43.900299h-127.004586a22.052243 22.052243 0 0 0-22.052243 21.848056zM496.175474 317.511466h-127.004587a22.052243 22.052243 0 1 0 0 43.900299h127.004587a22.052243 22.052243 0 0 0 0-43.900299zM657.687737 269.119043l46.146361-46.146361a22.052243 22.052243 0 0 0-31.036491-31.036491l-46.146361 46.146361a22.052243 22.052243 0 1 0 31.036491 31.036491zM454.725424 410.008375l-46.146361 46.146361A22.052243 22.052243 0 1 0 440.228116 487.395414l46.146361-46.146361a22.052243 22.052243 0 1 0-31.036491-31.036491zM626.651246 410.008375a22.052243 22.052243 0 0 0 0 31.03649l46.146361 46.146361a22.052243 22.052243 0 0 0 31.036491-31.03649l-46.146361-46.146361a22.052243 22.052243 0 0 0-31.036491 0zM470.243669 275.653041a22.052243 22.052243 0 0 0 15.518245-37.570489L440.228116 191.936191a22.052243 22.052243 0 0 0-31.036491 31.036491l46.146361 46.146361a21.848056 21.848056 0 0 0 14.905683 6.533998z" ></path></symbol><symbol id="icon-fenzu" viewBox="0 0 1024 1024"><path d="M512 1014.153846C234.673231 1014.153846 9.846154 789.326769 9.846154 512S234.673231 9.846154 512 9.846154 1014.153846 234.673231 1014.153846 512 789.326769 1014.153846 512 1014.153846z m0-57.934769c245.326769 0 444.219077-198.892308 444.219077-444.219077S757.326769 67.780923 512 67.780923 67.780923 266.673231 67.780923 512 266.673231 956.219077 512 956.219077z" ></path><path d="M507.116308 324.647385H276.361846v-43.34277h482.264616v43.34277H551.68v177.644307h175.812923v42.121846h-175.812923v195.347693h232.585846v42.732307H240.344615v-42.732307h95.842462v-293.021539h42.732308v293.021539h128.196923z" ></path></symbol><symbol id="icon-zu-copy" viewBox="0 0 1024 1024"><path d="M507.92 1023.64C29.72 941.976 24.2 248.376 24.2 241.384v-2.04l2.088-0.192C320.392 209.088 504.744 4.304 506.568 2.248l1.744-1.976 1.752 1.976c1.832 2.056 186.272 206.872 480.256 236.904l2.088 0.192v2.04c0 6.984-5.52 700.592-483.696 782.256l-0.4 0.048z m-31.688-457.584A262.272 262.272 0 0 0 544 669.816a451.488 451.488 0 0 1-147.264 47.576q12.688 17.672 21.752 33.08a452.52 452.52 0 0 0 153.384-58 357.688 357.688 0 0 0 137.976 55.28q10.872-16.8 25.824-36.704a345.928 345.928 0 0 1-132.536-40.552A295.352 295.352 0 0 0 685.808 565.6v-31.264h-237.44v31.72h27.864z m-190.992 23.104q28.088-14.496 53.472-27.64v128.688a15.424 15.424 0 0 1-17.672 17.216q-12.688 0-34.4-1.816 3.624 19.48 5.44 37.6 20.84 0.448 35.344 0 44.4-0.456 44.408-48v-150.4q26.048-13.368 48.936-24.92a362.4 362.4 0 0 1-3.624-36.248q-23.568 12.232-45.312 23.336v-85.92h51.656v-31.72h-51.696V301.432h-33.08v87.904h-54.4v31.72h54.4v101.952q-30.816 14.728-58 26.28z m145.904-68.424h34.4v-38.056h222.072v38.064h34.4V450.96h-59.36q22.656-34.888 43.048-71.144l-34.888-14.952q-20.616 43.728-44.864 86.096h-194.8v69.784zM718.4 349.912l-6.344-32.624Q587.024 329.976 434.32 333.6q3.624 17.224 6.344 33.08 136.84-5.44 277.768-16.8zM573.888 650.56a213.6 213.6 0 0 1-62.984-84.504h134.576a227.312 227.312 0 0 1-71.592 84.504z m0.456-209.12l30.816-14.048q-13.6-28.088-33.08-61.6l-28.544 12.688a642.152 642.152 0 0 1 30.816 62.984z m-86.544 6.344l29.904-15.856q-17.224-31.264-35.8-59.36l-28.096 14.048a516.28 516.28 0 0 1 33.984 61.168z" ></path></symbol><symbol id="icon-yiyao-gan" viewBox="0 0 1024 1024"><path d="M758 266.4c-0.3-0.3-0.7-0.3-1 0-7.2 1.8-14.5 2.8-22.1 3.1-7.1 0.3-14.1-0.2-20.9-1.6h-1.6c-3.7-1-7.5-1.8-11.2-2.5v0.5c-19.4-4.1-38.3-5.8-56.4-5.1-17 0-33.9 2.2-50.6 6.6h-0.5l-19.5 5.7c-11.6 2.7-27.1 0-46.6-8.2-2-0.7-4.1-1.4-6.2-2.1-34.7-12.2-81-16.9-138.7-13.8h-0.5c-62.1 2.7-113.5 25.4-154.1 68.1-40.6 42-61.8 93.9-63.5 155.6-1.7 59.8 10.2 127.1 35.9 201.8-2.8 40.6 1.3 72.8 12.3 96.8 0.6 2 1.8 3.4 3.5 4.1 1.7 0.6 3.6 0.6 5.7 0 61.4-22.6 97.9-56.7 109.5-102.5 12-26.9 42-46.1 90.1-57.3 30.4-6.8 68.5-32.1 114.2-75.8 135.1 27 242.9-54.2 323-243.6 0.8-1.4 1-3 0.6-4.7-2.7-15-13.6-24.4-32.8-28.2-16-3.7-38.9-2.6-68.6 3.1z m-22.5 18.4c8.2-0.3 16.5-1.5 25.1-3.5 26.9-5.1 47.9-6.1 63-3.1 10.5 2 17.2 6.9 19.9 14.4-4.3 10.1-8.7 19.8-13.2 29.3-74.2 157-170.5 225-289.1 203.9-2.1-0.5-4.3-0.9-6.5-1.3-1.3-0.4-2.5-0.4-3.5 0-1.3 0-2.4 0.5-3.1 1.5-5.4 5.1-10.6 9.9-15.7 14.6-37.7 33.8-69.1 53.8-94.3 60.2-54.7 12.3-88.3 34.3-101 66v1.5c-0.5 2.1-1 4.1-1.7 6.2-0.8 2.3-1.6 4.7-2.5 7-11.1 27.7-33.6 50.1-67.5 67.4-6.7 3.4-13.8 6.5-21.4 9.5-7.9-21.5-10.6-49.6-8.2-84.4 0-1.1-0.2-2.1-0.5-3.1-25.2-73.3-37-139.3-35.3-197.6 1.6-58.1 21.5-106.5 59.4-145.5 37.8-39.5 85.8-60.6 143.8-63.4 55.3-3.1 99.7 1.2 133.2 12.8h0.5c1.7 0.6 3.3 1.4 5 2h-0.5c23.6 10.3 42.5 13.2 56.9 8.7l19.4-5.6c15.7-4.1 31.5-6.1 47.1-6.1h0.5c17.1-0.7 34.7 0.8 52.8 4.5h0.5c3.7 0.7 7.3 1.6 10.7 2.6h2.1c7.9 1.4 15.9 1.9 24.1 1.5z" fill="#300403" ></path><path d="M687.7 320.7h-0.6c-15.7 0-31.4 2-47.1 6.1l-19.4 5.7c-9.6 3.1-21.2 2.7-34.9-1.1-3.7-1-7.5-2.2-11.2-3.6-9.6 20.5-17.6 46.6-24.1 78.4-11.7 57.7-14.8 97.6-9.2 119.6 118.6 21.1 214.9-46.9 289.1-203.9-8.4 0.8-17.5 2-27.5 3.9-8.5 2-16.9 3.3-25 3.6-8.2 0.3-16.2-0.2-24.1-1.6h-2c-3.5-1-7-1.8-10.8-2.5h-0.6c-18-3.7-35.6-5.2-52.6-4.6z m-144 6.1c-33-10.9-76.4-14.8-130-11.7-58 2.7-106 23.8-143.8 63.5-37.9 38.9-57.8 87.3-59.4 145.3-1.7 58.4 10.1 124.3 35.3 197.7 0.3 1 0.5 2 0.5 3-0.7 8.5-1 16.6-0.9 24.3 33.9-17.3 56.4-39.7 67.5-67.4v-1.4c0.7-1.9 1.6-3.8 2.5-5.6 0.7-2.1 1.2-4.1 1.7-6.2v-1.5c12.7-31.7 46.3-53.7 101-66 25.2-6.4 56.6-26.4 94.3-60.2-0.2-26.7 3.2-54.1 9.8-82.2 16.5-56.3 23.6-100.2 21.5-131.6z" fill="#DC892F" ></path></symbol><symbol id="icon-jiankangshequ" viewBox="0 0 1171 1024"><path d="M1161.63584 541.696L605.164983 7.753143A29.257143 29.257143 0 0 0 567.20384 6.582857L9.562697 541.915429a26.770286 26.770286 0 0 0-9.289143 23.917714 29.915429 29.915429 0 0 0 24.576 22.820571 33.206857 33.206857 0 0 0 29.257143-9.581714L146.486126 489.618286v510.317714a25.453714 25.453714 0 0 0 26.624 23.917714H997.137554a25.453714 25.453714 0 0 0 26.624-23.917714V490.788571l92.525715 88.649143a32.841143 32.841143 0 0 0 29.257142 9.581715 29.257143 29.257143 0 0 0 24.941715-22.820572 24.429714 24.429714 0 0 0-8.557715-24.502857z m-360.886857 146.285714l-1.755429 1.755429c-12.068571 11.337143-141.458286 129.974857-187.684571 170.715428a23.990857 23.990857 0 0 1-32.475429 0c-46.445714-40.594286-175.542857-159.232-187.318857-170.569142l-1.755428-1.755429a150.528 150.528 0 0 1-36.571429-97.572571 148.553143 148.553143 0 0 1 238.811429-117.394286l0.585142 0.585143v-0.585143l1.755429 1.170286 1.755429-1.170286v0.585143l0.585142-0.585143a151.552 151.552 0 0 1 90.916572-30.573714 148.699429 148.699429 0 0 1 149.284571 147.968 151.186286 151.186286 0 0 1-36.059428 97.426285z" ></path></symbol><symbol id="icon-nanxing" viewBox="0 0 1024 1024"><path d="M592.896 382.839467a273.066667 273.066667 0 1 0 48.3328 48.3328l112.093867-112.093867 0.068266 110.660267a34.133333 34.133333 0 0 0 68.266667 0l-0.068267-193.3312a34.133333 34.133333 0 0 0-34.2016-34.133334l-192.989866 0.2048a34.065067 34.065067 0 1 0 0.136533 68.266667l110.7968-0.136533-112.4352 112.2304zM512 1024a512 512 0 1 1 0-1024 512 512 0 0 1 0 1024z m58.299733-570.299733a204.8 204.8 0 1 1-289.518933 289.655466 204.8 204.8 0 0 1 289.518933-289.655466z" ></path></symbol><symbol id="icon-zheng" viewBox="0 0 1024 1024"><path d="M510.439136 47.65007c255.268231 0 462.954464 207.618161 462.954464 462.886392s-207.686233 462.886392-462.954464 462.886392c-255.20016 0-462.818321-207.618161-462.818321-462.886392s207.618161-462.886392 462.818321-462.886392m0-47.65007a510.536462 510.536462 0 1 0 0.204214 1021.140996A510.536462 510.536462 0 0 0 510.439136 0z" fill="#0d6eff" ></path><path d="M393.083821 576.021272c1.497574 13.478163 5.241508 30.223759 11.027588 50.30486a2328.250482 2328.250482 0 0 0-105.919298 110.616233l-32.94662-37.643555c11.57216-16.201024 17.35824-35.465266 17.35824-57.996942v-181.070265H212.558128v-41.659776h114.564382v225.657117c17.766669-16.813667 39.753773-39.685701 65.961311-68.207672zM268.717139 234.574486a3192.350462 3192.350462 0 0 1 94.89171 99.520575l-40.502559 34.171907a1268.853287 1268.853287 0 0 0-89.718274-102.992222l35.329123-30.70026z m90.262846 486.711428h80.460547V401.281659h44.586851v320.004255h92.032706V298.221365H390.769389v-42.816991h386.578209v42.816991H622.280657v174.195041h134.305125v42.816992H622.280657v205.984444h164.392741v42.816991H358.979985v-42.748919z" fill="#0d6eff" ></path></symbol><symbol id="icon-tanged" viewBox="0 0 1446 1024"><path d="M1196.87625 304.43375h-1051.675v-27.67625c0-106.83125 86.9-193.73 193.73125-193.73h664.21375c106.83125 0 193.73 86.89875 193.73 193.73v27.67625z" fill="" ></path><path d="M203.33125 249.0825h935.415c-13.2375-64.385-69.86875-110.62-135.6-110.70375H338.9325c-65.7325 0.08375-122.36375 46.31875-135.60125 110.70375zM117.52625 359.785h1107.02625c15.28375 0 27.67625 12.3875 27.67625 27.67625 0 15.2825-12.3925 27.675-27.67625 27.675H117.52625a27.68375 27.68375 0 0 1-19.57125-8.105 27.67875 27.67875 0 0 1-8.105-19.57c0-15.28875 12.3925-27.67625 27.67625-27.67625zM629.5275 0h83.0275c22.925 0 41.50875 18.58375 41.50875 41.51375 0 22.925-18.58375 41.51375-41.50875 41.51375h-83.0275c-22.93 0-41.51375-18.58875-41.51375-41.51375 0-22.93 18.58375-41.51375 41.51375-41.51375z m0 0" fill="" ></path><path d="M1003.14625 1023.99875H338.9325c-106.83125 0-193.73125-86.8975-193.73125-193.73V359.785h1051.675v470.4825c0 106.83375-86.9 193.73125-193.73 193.73125zM576.235 744.84375a41.045 41.045 0 0 1-8.69125-15.14125c-4.18875-12.71-2.67125-27.14875 4.5025-42.92 31.72875-69.7625-8.58-112.71-10.3125-114.5125-9.585-9.94125-25.415-10.22375-35.35625-0.63875-9.9425 9.58875-10.23 25.42-0.64 35.36125a40.45 40.45 0 0 1 6.26 12.71c4.17 13.65625 2.32875 29.2675-5.46375 46.41125-16.50875 36.27875-11.88 65.25875-5.08875 83.1775a92.0325 92.0325 0 0 0 15 26.00125 25.6875 25.6875 0 0 0 3.53 3.99875c1.11875 1.1575 1.9975 1.9975 2.4325 2.37875l0.23875-0.27c10.3175 7.31875 24.4725 5.77625 32.97375-3.5875 8.50125-9.37 8.6675-23.61 0.38625-33.16875l0.22875 0.2z m116.5825 0a40.66875 40.66875 0 0 1-8.71125-15.14125c-4.19-12.71-2.68125-27.14875 4.4975-42.92 31.72375-69.7625-8.57875-112.71-10.3175-114.5125-9.59-9.94125-25.42-10.22375-35.36125-0.63875-9.94125 9.58875-10.23 25.42-0.64 35.36125a40.06625 40.06625 0 0 1 6.27 12.71c4.16 13.65625 2.32875 29.2675-5.46875 46.41125-16.49875 36.27875-11.87 65.25875-5.0925 83.1775a92.4025 92.4025 0 0 0 15 26.00125 25.7175 25.7175 0 0 0 3.54 3.99875c1.1125 1.1575 2.00125 1.9975 2.42125 2.37875l0.24875-0.27c10.3325 7.09125 24.30625 5.45375 32.725-3.81875 8.4175-9.2775 8.69125-23.34375 0.635-32.93875l0.25375 0.20125z m109.0575 0a40.8275 40.8275 0 0 1-8.72125-15.14125c-4.18-12.71-2.67125-27.14875 4.5025-42.92 31.72875-69.7625-8.57875-112.71-10.3125-114.5125-9.585-9.94125-25.42-10.22375-35.35625-0.63875-9.94125 9.58875-10.23 25.42-0.645 35.36125a39.975 39.975 0 0 1 6.275 12.71c4.16 13.65625 2.31875 29.2675-5.47375 46.41125-16.49875 36.27875-11.88 65.25875-5.0875 83.1775a91.9125 91.9125 0 0 0 15 26.00125 25.21125 25.21125 0 0 0 3.54 3.99875 51.74125 51.74125 0 0 0 2.4175 2.37875l0.24375-0.27c10.3175 7.31875 24.4725 5.77625 32.97375-3.5875 8.50125-9.37 8.6675-23.61 0.38625-33.16875l0.2575 0.2z" fill="" ></path></symbol><symbol id="icon-xiangshang" viewBox="0 0 1026 1024"><path d="M839.97683371 210.33526043q30.05911996-30.05911996 72.4639499-30.05911996t72.46394989 30.05911996q31.13265995 30.05911996 31.13265996 71.9271799t-31.13265996 71.92717989l-401.50395943 399.35687944q-12.88247998 15.02955998-32.20619994 20.93402997t-40.79451995 4.83093-42.40482994-9.12509-35.96358995-23.08110996l-395.06271944-392.91563945q-31.13265995-30.05911996-31.13265996-71.92717989t31.13265996-71.9271799q15.02955998-15.02955998 33.81650995-22.54433997t38.64743994-7.51477999 39.18420995 7.51477999 34.35327995 22.54433997l328.50323953 324.20907954z" ></path></symbol><symbol id="icon-dianhua" viewBox="0 0 1024 1024"><path d="M512 64C265.6 64 64 265.6 64 512s201.6 448 448 448 448-201.6 448-448S758.4 64 512 64z m163.2 681.6c-156.8 0-393.6-249.6-393.6-384 0-51.2 44.8-89.6 83.2-89.6 41.6 0 108.8 115.2 108.8 140.8 0 16-6.4 28.8-12.8 38.4-3.2 6.4-6.4 12.8-6.4 19.2 6.4 19.2 76.8 89.6 99.2 99.2 6.4 0 12.8-3.2 19.2-6.4 12.8-6.4 25.6-12.8 41.6-12.8 28.8 0 144 76.8 144 108.8 0 57.6-35.2 86.4-83.2 86.4z" ></path></symbol><symbol id="icon-miandangou" viewBox="0 0 1024 1024"><path d="M512 1012c-275.7 0-500-224.3-500-500S236.3 12 512 12s500 224.3 500 500-224.3 500-500 500z m0-942.76C267.86 69.24 69.25 267.86 69.25 512S267.86 954.76 512 954.76c244.13 0 442.75-198.62 442.75-442.76S756.14 69.24 512 69.24z" ></path><path d="M347.66 415.6h162.13c3.39 0 6.7-1.19 9.29-3.37 18.09-15.23 35.25-31.23 51.48-48.01 8.72-9.02 2.25-24.15-10.29-24.15H418c-3.99 0-7.73 1.69-10.4 4.65-32.82 36.32-71.5 69.42-116.05 99.28-6.1 4.09-14.4 2.78-19.02-2.93l-0.73-0.9c-5.33-6.59-3.65-16.25 3.45-20.87 64.11-41.8 115.99-92.69 155.65-152.69 3.24-4.9 9.07-7.35 14.81-6.1l1.11 0.24c9.85 2.15 14.35 13.51 8.73 21.88-5.99 8.94-13 18.83-21.02 29.67h182.38c7.85 0 14.22 6.36 14.22 14.22v3.96c0 3.33-1.19 6.63-3.32 9.19-25.48 30.75-50.11 56.07-73.88 75.94h130.18c7.85 0 14.22 6.36 14.22 14.22v132.08c0 7.85-6.36 14.22-14.22 14.22H570.59V699.4c0 19.25 8.88 28.88 26.65 28.88H690c11.85 0 20.17-3.52 24.99-10.55 5.38-7.91 9.28-28.53 11.68-61.88 0.66-9.17 9.66-15.41 18.43-12.66l0.27 0.08c6.29 1.97 10.44 8.05 9.93 14.62-3.55 45.6-9.94 74.07-19.21 85.38-8.51 9.63-21.85 14.44-39.99 14.44H588.35c-31.85 0-47.75-17.41-47.75-52.2V590.33c0-7.85-6.36-14.22-14.22-14.22h-22.45c-3.26 9.43-7.42 20.1-12.45 32.03-0.18 0.43-0.38 0.87-0.59 1.3-30.99 62.55-97.23 113.69-198.76 153.42-5.77 2.26-12.45 0.48-16.35-4.33-5.98-7.4-3.2-18.58 5.65-22.08 86.74-34.36 145.6-77.59 176.59-129.69 0.26-0.43 0.5-0.87 0.73-1.32 1.52-2.95 2.97-5.9 4.36-8.86 4.48-9.51-2.26-20.46-12.77-20.46H347.66c-7.85 0-14.22-6.36-14.22-14.22V429.82c0-7.86 6.37-14.22 14.22-14.22z m133.51 131.63c8.14-32.95 12.77-67.38 13.88-103.3H377.64c-7.85 0-14.22 6.36-14.22 14.22v74.87c0 7.85 6.36 14.22 14.22 14.22h103.53z m187.72-14.22v-74.87c0-7.85-6.36-14.22-14.22-14.22H525.04c-1.1 39.62-5.37 74.06-12.77 103.3h142.4c7.85 0.01 14.22-6.36 14.22-14.21z" ></path><path d="M286.89 778.16c-8.45 0-16.65-3.75-22.22-10.64-5.7-7.05-7.72-16.49-5.42-25.26 2.31-8.81 8.48-15.79 16.92-19.14 83.32-33 140.37-74.62 169.56-123.69 1.74-3.35 3.12-6.16 4.45-8.97l-102.51-0.04c-15.73 0-28.53-12.79-28.53-28.52V442.26c-6.42 4.63-12.96 9.17-19.62 13.63-12.17 8.13-28.9 5.58-38.11-5.81-5.77-7.12-7.95-15.23-6.7-23.14 1.26-8.02 5.9-15.16 12.73-19.62 62.17-40.52 113.14-90.52 151.53-148.59 6.55-9.92 18.19-14.77 29.8-12.2 10.34 2.26 17.96 8.69 21.48 17.44 3.54 8.79 2.49 18.74-2.8 26.63-1.61 2.4-3.28 4.86-5.04 7.39h154.52c15.73 0 28.52 12.8 28.52 28.53v3.96c0 6.67-2.35 13.17-6.61 18.32-16.21 19.57-32.23 37.12-47.91 52.5h93.19c15.73 0 28.52 12.79 28.52 28.52V561.9c0 15.73-12.79 28.52-28.52 28.52h-99.2V699.4c0 13.58 4.66 14.56 12.33 14.56h92.76c6.78 0 11.22-1.45 13.18-4.33 0.96-1.41 6.04-10.88 9.21-54.81 0.64-8.81 5.19-16.7 12.48-21.66 7.24-4.92 16.18-6.24 24.51-3.63 13.03 4.08 21.22 16.16 20.18 29.47-5.07 65.33-15.21 84.55-22.4 93.33-11.66 13.21-28.72 19.69-51.07 19.69H588.35c-40.03 0-62.07-23.63-62.07-66.52V590.33l-12.28 0.05c-2.65 7.09-5.74 14.79-9.34 23.32l-0.98 2.14c-32.45 65.5-101.88 119.47-206.34 160.34-3.4 1.34-6.95 1.98-10.45 1.98zM450.34 561.8c9.8 0 18.78 4.93 24.02 13.19 5.3 8.35 5.93 18.69 1.71 27.68-1.46 3.1-2.98 6.18-4.58 9.29-0.38 0.73-0.77 1.43-1.17 2.12-32.49 54.62-94.27 100.26-183.61 135.65 97.85-38.41 162.16-87.68 191.37-146.65 5.27-12.45 9.23-22.63 12.34-31.64l3.33-9.64h32.65c15.73 0 28.52 12.8 28.52 28.53v115.18c0 33.3 16.07 37.9 33.44 37.9H696.1c13.79 0 23.63-3.24 29.27-9.61 2.21-2.7 7.3-12.03 11.6-40.23-3.18 19.46-6.92 27.47-10.14 32.21-5.27 7.69-15.91 16.81-36.83 16.81h-92.76c-25.65 0-40.96-16.14-40.96-43.19V561.8H684.1l-0.1-131.99-25.76 0.02c14.05 1.76 24.96 13.78 24.96 28.31V533c0 15.73-12.8 28.53-28.53 28.53H493.9l4.5-17.82c7.12-28.15 11.27-61.86 12.34-100.19l0.38-13.64c-0.43 0.01-0.87 0.03-1.31 0.03l-0.45 14.45c-1.14 36.73-5.95 72.49-14.29 106.29l-2.68 10.88H377.65c-15.73 0-28.52-12.8-28.52-28.53v-74.86c0-14.33 10.61-26.22 24.38-28.23h-25.75v131.98l102.58-0.09z m-72.69-103.57l0.1 74.77 92.07-0.08c5.29-24.02 8.73-49.06 10.26-74.69H377.65z m152.51 74.69h124.42v-74.77l-115.76 0.08c-1.31 27.28-4.22 52.29-8.66 74.69z m-86.51-258.27c-41.39 61.21-95.14 113.96-160.6 156.64 43.88-28.23 82.03-60.87 113.92-96.16 3.82-4.22 8.78-7.16 14.19-8.52h-5.02l16.88-22.82c7.87-10.65 14.75-20.36 20.63-29.14z m-95.99 145.91l-0.01 9.35h0.01v-9.35z m166.27 9.05l1.13-0.19c-0.37 0.07-0.75 0.14-1.13 0.19z m-143.38-28.32h139.24a663.188 663.188 0 0 0 50.48-47.02l-142.28 0.12c-14.57 16.19-30.42 31.86-47.44 46.9z m196.36-74.74c8.7 2.08 16.07 8.16 19.66 16.67 2.91 6.86 2.98 14.39 0.5 21.08 9.78-10.41 19.69-21.67 29.71-33.76l0.03-4.01-49.9 0.02z" ></path></symbol></svg>',l=(c=document.getElementsByTagName("script"))[c.length-1].getAttribute("data-injectcss");if(l&&!v.__iconfont__svg__cssinject__){v.__iconfont__svg__cssinject__=!0;try{document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>")}catch(c){console&&console.log(c)}}!function(c){if(document.addEventListener)if(~["complete","loaded","interactive"].indexOf(document.readyState))setTimeout(c,0);else{var l=function(){document.removeEventListener("DOMContentLoaded",l,!1),c()};document.addEventListener("DOMContentLoaded",l,!1)}else document.attachEvent&&(a=c,h=v.document,t=!1,o=function(){t||(t=!0,a())},(i=function(){try{h.documentElement.doScroll("left")}catch(c){return void setTimeout(i,50)}o()})(),h.onreadystatechange=function(){"complete"==h.readyState&&(h.onreadystatechange=null,o())});var a,h,t,o,i}(function(){var c,l;(c=document.createElement("div")).innerHTML=a,a=null,(l=c.getElementsByTagName("svg")[0])&&(l.setAttribute("aria-hidden","true"),l.style.position="absolute",l.style.width=0,l.style.height=0,l.style.overflow="hidden",function(c,l){l.firstChild?function(c,l){l.parentNode.insertBefore(c,l)}(c,l.firstChild):l.appendChild(c)}(l,document.body))})}(window);
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Details for upgrading vault. * */ class UpgradeDetails { /** * Create a UpgradeDetails. * @member {string} [operationId] ID of the vault upgrade operation. * @member {date} [startTimeUtc] UTC time at which the upgrade operation has * started. * @member {date} [lastUpdatedTimeUtc] UTC time at which the upgrade * operation status was last updated. * @member {date} [endTimeUtc] UTC time at which the upgrade operation has * ended. * @member {string} [status] Status of the vault upgrade operation. Possible * values include: 'Unknown', 'InProgress', 'Upgraded', 'Failed' * @member {string} [message] Message to the user containing information * about the upgrade operation. * @member {string} [triggerType] The way the vault upgradation was * triggered. Possible values include: 'UserTriggered', 'ForcedUpgrade' * @member {string} [upgradedResourceId] Resource ID of the upgraded vault. * @member {string} [previousResourceId] Resource ID of the vault before the * upgrade. */ constructor() { } /** * Defines the metadata of UpgradeDetails * * @returns {object} metadata of UpgradeDetails * */ mapper() { return { required: false, serializedName: 'UpgradeDetails', type: { name: 'Composite', className: 'UpgradeDetails', modelProperties: { operationId: { required: false, readOnly: true, serializedName: 'operationId', type: { name: 'String' } }, startTimeUtc: { required: false, readOnly: true, serializedName: 'startTimeUtc', type: { name: 'DateTime' } }, lastUpdatedTimeUtc: { required: false, readOnly: true, serializedName: 'lastUpdatedTimeUtc', type: { name: 'DateTime' } }, endTimeUtc: { required: false, readOnly: true, serializedName: 'endTimeUtc', type: { name: 'DateTime' } }, status: { required: false, readOnly: true, serializedName: 'status', type: { name: 'String' } }, message: { required: false, readOnly: true, serializedName: 'message', type: { name: 'String' } }, triggerType: { required: false, readOnly: true, serializedName: 'triggerType', type: { name: 'String' } }, upgradedResourceId: { required: false, readOnly: true, serializedName: 'upgradedResourceId', type: { name: 'String' } }, previousResourceId: { required: false, readOnly: true, serializedName: 'previousResourceId', type: { name: 'String' } } } } }; } } module.exports = UpgradeDetails;
describe('Location Blacklist Controller', function () { var $scope, $controller, $parentScope, $httpBackend, Table, Modal, Notifications; beforeEach(module('adminNg')); beforeEach(module(function ($provide) { $provide.value('Language', { configureFromServer: function () {}, formatDate: function (val, date) { return date; }, formatDateTime: function (val, date) { return date; }, formatDateTimeRaw: function (val, date) { return date; }, formatTime: function (val, date) { return date; } }); })); beforeEach(inject(function ($rootScope, _$controller_, _$httpBackend_, _Table_, _Modal_, _Notifications_) { $controller = _$controller_; Notifications = _Notifications_; Modal = _Modal_; Table = _Table_; $httpBackend = _$httpBackend_; $parentScope = $rootScope.$new(); $scope = $parentScope.$new(); $controller('LocationblacklistCtrl', {$scope: $scope}); })); beforeEach(function () { jasmine.getJSONFixtures().fixturesPath = 'base/app/GET'; $httpBackend.whenGET('/admin-ng/resources/BLACKLISTS.LOCATIONS.REASONS.json') .respond('{}'); $httpBackend.whenGET('/admin-ng/capture-agents/agents.json') .respond(JSON.stringify(getJSONFixture('admin-ng/capture-agents/agents.json'))); $httpBackend.whenGET('/blacklist/blacklists.json?limit=10&offset=0&type=room') .respond('{}'); }); it('instantiates and provides the states', function () { expect($scope.states).toBeDefined(); }); describe('when editing', function () { beforeEach(function () { $scope.action = 'edit'; Modal.$scope = { resourceId: '241' }; }); it('fetches location blacklist data', function () { $httpBackend.expectGET('/blacklist/241?type=room') .respond(JSON.stringify(getJSONFixture('blacklist/241'))); $controller('LocationblacklistCtrl', {$scope: $scope}); $httpBackend.flush(); }); it('populates user data', function () { $httpBackend.whenGET('/blacklist/241?type=room') .respond(JSON.stringify(getJSONFixture('blacklist/241'))); $controller('LocationblacklistCtrl', {$scope: $scope}); $httpBackend.flush(); expect($scope.states[0].stateController.ud.items.length).toBe(1); expect($scope.states[1].stateController.ud.fromDate).toBeDefined(); expect($scope.states[2].stateController.ud.reason).toBeDefined(); }); }); describe('#submit', function () { beforeEach(function () { Modal.$scope = { close: jasmine.createSpy() }; $httpBackend.whenGET('/admin-ng/capture-agents/agents.json') .respond(JSON.stringify(getJSONFixture('admin-ng/capture-agents/agents.json'))); spyOn(Table, 'fetch'); spyOn(Notifications, 'add'); $scope.states = [{ name: 'items', stateController: { ud: { items: [ { id: 912 } ] } } }, { name: 'dates', stateController: { ud: { fromDate: '2014-07-01', toDate: '2014-12-01', fromTime: '10:54', toTime: '23:31' } } }, { name: 'reason', stateController: { ud: { fancy: 'permission' } } }]; }); describe('when creating', function () { it('saves collected userdata', function () { $httpBackend.expectPOST('/blacklist').respond(201); $scope.submit(); $httpBackend.flush(); }); describe('on success', function () { beforeEach(function () { $httpBackend.whenPOST('/blacklist').respond(201); }); it('shows a notification and refreshes the table', function () { $scope.submit(); $httpBackend.flush(); expect(Table.fetch).toHaveBeenCalled(); expect(Notifications.add).toHaveBeenCalledWith('success', jasmine.any(String)); }); it('closes the modal', function () { $scope.submit(); $httpBackend.flush(); expect(Modal.$scope.close).toHaveBeenCalled(); }); }); describe('on error', function () { beforeEach(function () { $httpBackend.whenPOST('/blacklist').respond(500); }); it('shows a notification', function () { $scope.submit(); $httpBackend.flush(); expect(Table.fetch).not.toHaveBeenCalled(); expect(Notifications.add).toHaveBeenCalledWith('error', jasmine.any(String), jasmine.any(String)); }); }); }); describe('when editing', function () { beforeEach(function () { $scope.action = 'edit'; }); it('saves collected userdata', function () { $httpBackend.expectPUT('/blacklist') .respond(JSON.stringify(getJSONFixture('blacklist/241'))); $scope.submit(); $httpBackend.flush(); }); describe('on success', function () { beforeEach(function () { $httpBackend.whenPUT('/blacklist') .respond(JSON.stringify(getJSONFixture('blacklist/241'))); }); it('shows a notification and refreshes the table', function () { $scope.submit(); $httpBackend.flush(); expect(Table.fetch).toHaveBeenCalled(); expect(Notifications.add).toHaveBeenCalledWith('success', jasmine.any(String)); }); it('closes the modal', function () { $scope.submit(); $httpBackend.flush(); expect(Modal.$scope.close).toHaveBeenCalled(); }); }); describe('on error', function () { beforeEach(function () { $httpBackend.whenPUT('/blacklist').respond(500); }); it('shows a notification', function () { $scope.submit(); $httpBackend.flush(); expect(Table.fetch).not.toHaveBeenCalled(); expect(Notifications.add).toHaveBeenCalledWith('error', jasmine.any(String), jasmine.any(String)); }); }); }); }); });
import React, { Component } from 'react' import { connect } from 'dva' import moment from 'moment' import BooleanOption from '../../components/BooleanOption'; import BaseTool from '../../common/Base.tool' import { Tag, Button, Row, Col, Icon, Card, Tabs, Table, Radio, DatePicker, Tooltip, Menu, Dropdown,Badge, Switch,Select,Form,AutoComplete,Modal } from 'antd' import { Link, Route, Redirect} from 'dva/router' import numeral from 'numeral' import {TagCloud} from '../../components/Charts' import Trend from '../../components/Trend' import NumberInfo from '../../components/NumberInfo' import { getTimeDistance } from '../../utils/utils' import PageHeaderLayout from '../../layouts/PageHeaderLayout' import styles from './CustomerContract.workbench.less' import DescriptionList from '../../components/DescriptionList'; import ImagePreview from '../../components/ImagePreview'; import GlobalComponents from '../../custcomponents'; import DashboardTool from '../../common/Dashboard.tool' import appLocaleName from '../../common/Locale.tool' const {aggregateDataset,calcKey, defaultHideCloseTrans, defaultImageListOf,defaultSettingListOf,defaultBuildTransferModal, defaultExecuteTrans,defaultHandleTransferSearch,defaultShowTransferModel, defaultRenderExtraHeader, defaultSubListsOf,defaultRenderAnalytics, defaultRenderExtraFooter,renderForTimeLine,renderForNumbers, defaultQuickFunctions, defaultRenderSubjectList, }= DashboardTool const {defaultFormatNumber} = BaseTool const formatNumber = defaultFormatNumber const { Description } = DescriptionList; const { TabPane } = Tabs const { RangePicker } = DatePicker const { Option } = Select const imageList =(customerContract)=>{return [ ]} const internalImageListOf = (customerContract) =>defaultImageListOf(customerContract,imageList) const optionList =(customerContract)=>{return [ ]} const buildTransferModal = defaultBuildTransferModal const showTransferModel = defaultShowTransferModel const internalRenderSubjectList = defaultRenderSubjectList const internalSettingListOf = (customerContract) =>defaultSettingListOf(customerContract, optionList) const internalLargeTextOf = (customerContract) =>{ return null } const internalRenderExtraHeader = defaultRenderExtraHeader const internalRenderExtraFooter = defaultRenderExtraFooter const internalSubListsOf = defaultSubListsOf const renderSettingDropDown = (cardsData,targetComponent)=>{ return (<div style={{float: 'right'}} > <Dropdown overlay={renderSettingMenu(cardsData,targetComponent)} placement="bottomRight" > <Button> <Icon type="setting" theme="filled" twoToneColor="#00b" style={{color:'#3333b0'}}/> 设置 <Icon type="down"/> </Button> </Dropdown></div>) } const renderSettingMenuItem = (item,cardsData,targetComponent) =>{ const userContext = null return (<Menu.Item key={item.name}> <Link to={`/customerContract/${targetComponent.props.customerContract.id}/list/${item.name}/${item.displayName}/`}> <span>{item.displayName}</span> </Link> </Menu.Item> ) } const renderSettingMenu = (cardsData,targetComponent) =>{ const userContext = null return (<Menu> <Menu.Item key="profile"> <Link to={`/customerContract/${targetComponent.props.customerContract.id}/permission`}><Icon type="safety-certificate" theme="twoTone" twoToneColor="#52c41a"/><span>{appLocaleName(userContext,"Permission")}</span></Link> </Menu.Item> <Menu.Divider /> {cardsData.subSettingItems.map(item=>renderSettingMenuItem(item,cardsData,targetComponent))} </Menu>) } const internalRenderTitle = (cardsData,targetComponent) =>{ const linkComp=cardsData.returnURL?<Link to={cardsData.returnURL}> <Icon type="double-left" style={{marginRight:"10px"}} /> </Link>:null return (<div>{linkComp}{cardsData.cardsName}: {cardsData.displayName} {renderSettingDropDown(cardsData,targetComponent)}</div>) } const internalSummaryOf = (cardsData,targetComponent) =>{ const quickFunctions = targetComponent.props.quickFunctions || internalQuickFunctions const customerContract = cardsData.cardsSource const {CustomerContractService} = GlobalComponents const userContext = null return ( <div> <DescriptionList className={styles.headerList} size="small" col="4"> <Description term="ID" style={{wordBreak: 'break-all'}}>{customerContract.id}</Description> <Description term="名称" style={{wordBreak: 'break-all'}}>{customerContract.name}</Description> <Description term="接触时间">{ moment(customerContract.contactTime).format('YYYY-MM-DD HH:mm')}</Description> <Description term="客户">{customerContract.customer==null?appLocaleName(userContext,"NotAssigned"):`${customerContract.customer.displayName}(${customerContract.customer.id})`} </Description> </DescriptionList> </div> ) } const renderTagCloud=(cardsData)=>{ if(cardsData.subItems.length<10){ return null } const tagValue = cardsData.subItems.map(item=>({name:item.displayName, value: item.count})) return <div > <div style={{verticalAlign:"middle",textAlign:"center",backgroundColor:"rgba(0, 0, 0, 0.65)",color:"white",fontWeight:"bold",height:"40px"}}> <span style={{display:"inline-block",marginTop:"10px"}}>{`${cardsData.displayName}画像`}</span> </div> <TagCloud data={tagValue} height={200} style={{backgroundColor:"white"}}/> </div> } const internalQuickFunctions = defaultQuickFunctions class CustomerContractWorkbench extends Component { state = { transferModalVisiable: false, candidateReferenceList: {}, candidateServiceName:"", candidateObjectType:"city", targetLocalName:"", transferServiceName:"", currentValue:"", transferTargetParameterName:"", defaultType: 'customerContract' } componentDidMount() { } render() { // eslint-disable-next-line max-len const { id,displayName, } = this.props.customerContract if(!this.props.customerContract.class){ return null } const returnURL = this.props.returnURL const cardsData = {cardsName:window.trans('customer_contract'),cardsFor: "customerContract", cardsSource: this.props.customerContract,returnURL,displayName, subItems: [ ], subSettingItems: [ ], }; const renderExtraHeader = this.props.renderExtraHeader || internalRenderExtraHeader const settingListOf = this.props.settingListOf || internalSettingListOf const imageListOf = this.props.imageListOf || internalImageListOf const subListsOf = this.props.subListsOf || internalSubListsOf const largeTextOf = this.props.largeTextOf ||internalLargeTextOf const summaryOf = this.props.summaryOf || internalSummaryOf const renderTitle = this.props.renderTitle || internalRenderTitle const renderExtraFooter = this.props.renderExtraFooter || internalRenderExtraFooter const renderAnalytics = this.props.renderAnalytics || defaultRenderAnalytics const quickFunctions = this.props.quickFunctions || internalQuickFunctions const renderSubjectList = this.props.renderSubjectList || internalRenderSubjectList // {quickFunctions(cardsData)} return ( <PageHeaderLayout title={renderTitle(cardsData,this)} content={summaryOf(cardsData,this)} wrapperClassName={styles.advancedForm} > {renderExtraHeader(cardsData.cardsSource)} {imageListOf(cardsData.cardsSource,4)} {renderAnalytics(cardsData.cardsSource)} {settingListOf(cardsData.cardsSource)} {largeTextOf(cardsData.cardsSource)} </PageHeaderLayout> ) } } export default connect(state => ({ customerContract: state._customerContract, returnURL: state.breadcrumb.returnURL, }))(Form.create()(CustomerContractWorkbench))
module.exports = (sequelize, DataTypes) => { return sequelize.define("warns", { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, }, server: DataTypes.STRING, user: DataTypes.STRING, warnedBy: DataTypes.STRING, reason: DataTypes.TEXT, }); }
var webpack = require('webpack'); var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { index:'./public/html/js/index.js', main:'./public/html/js/main.js' }, output: { filename: '[name].js' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }] }, plugins: [ //new webpack.optimize.UglifyJsPlugin({ // compress: { // warnings: false, // }, // output: { // comments: false, // }, //}),//压缩和丑化 new webpack.ProvidePlugin({ $: 'jquery' }),//直接定义第三方库 new CommonsChunkPlugin({ name: "commons", // (the commons chunk name) filename: "commons.js", // (the filename of the commons chunk) minChunks: 2, // (Modules must be shared between 3 entries) chunks: ["index", "main"] // (Only use these entries) })//定义公共chunk ] }; /*module.exports = { entry: ['./src/index'], // file extension after index is optional for .js files output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, devServer: { contentBase: "./src",//本地服务器所加载的页面所在的目录 colors: true,//终端中输出结果为彩色 historyApiFallback: true,//不跳转 inline: true//实时刷新 }, module: { //加载器配置 loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurenceOrderPlugin() ] }*/
'use strict'; var gulp = require("gulp"); var sass = require("gulp-sass"); var plumber = require("gulp-plumber"); var postcss = require("gulp-postcss"); var autoprefixer = require("autoprefixer"); var mqpacker = require("css-mqpacker"); // consolidate all styles var minify = require("gulp-csso"); // minification css var server = require("browser-sync"); var svgSprite = require('gulp-svg-sprite'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var gutil = require('gulp-util'); var rename = require('gulp-rename'); var filesize = require('gulp-filesize'); var imagemin = require("gulp-imagemin"); var del = require("del"); var run = require("run-sequence"); var ghPages = require('gulp-gh-pages'); /*======================================= = SASS task = =======================================*/ gulp.task("style", function() { gulp.src("src/sass/style.scss") .pipe(plumber()) .pipe(sass()) .pipe(postcss([ autoprefixer({browsers: ['last 4 version', 'ie 11']}), mqpacker({ sort: true }) ])) .pipe(gulp.dest("build/css")) .pipe(minify()) .pipe(rename("style.min.css")) .pipe(gulp.dest("build/css")) .pipe(server.reload({stream: true})); }); /*======================================= = IMGmin task = =======================================*/ gulp.task("images", function() { return gulp.src("build/img/**/*.{png,jpg,gif,svg}") .pipe(imagemin([ imagemin.optipng({optimizationLevel: 3}), imagemin.jpegtran({progressive: true}), imagemin.svgo({minifyStyles: true, removeDoctype: true}) ])) .pipe(gulp.dest("build/img")); }); /*======================================= = SVG-Sprite task = =======================================*/ gulp.task('svg', function() { return gulp.src('src/_assets/svg-sprite/*.svg') .pipe(svgSprite({ mode: { symbol: { dest: '.', dimensions: '%s', sprite: 'build/img/svg-sprite.svg', example: false, render: {scss: {dest: 'src/sass/global/_svg-sprite.scss'}} } }, svg: { xmlDeclaration: false, doctypeDeclaration: false } })) .pipe(gulp.dest('./')); }); /*======================================= = JavaScript task = =======================================*/ gulp.task('js', function() { return gulp.src(['src/js/plugins/*.js', 'src/js/vendor/*.js', 'src/js/modules/*.js', 'src/js/main.js']) .pipe(concat('scripts.js')) .pipe(gulp.dest('build/js/')) .pipe(filesize()) .pipe(uglify()) .pipe(rename('scripts.min.js')) .pipe(gulp.dest('build/js/')) .pipe(filesize()) .on('error', gutil.log) }); /*======================================= = copy into build = =======================================*/ gulp.task("copy", function() { return gulp.src([ "src/img/**", "src/js/jquery.fancybox.js" // "src/*.html" ], { base: "src/" }) .pipe(gulp.dest("build")); }); /*======================================= = copy HTML into build = =======================================*/ gulp.task("copyHTML", function() { return gulp.src([ "src/*.html", "src/favicon.ico" ], { base: "src/" }) .pipe(gulp.dest("build")); }); gulp.task("serve", function() { server.init({ server: "build" }); gulp.watch("src/sass/**/*.{scss,sass}", ["style"]); gulp.watch("src/*.html", ["copyHTML"]).on("change", server.reload); }); gulp.task("clean", function() { return del("build"); }); gulp.task("build", function(fn) { run( "clean", "copy", "copyHTML", "style", "images", "svg", "js", fn); }); /*======================================= = deploy to gh-pages = =======================================*/ gulp.task('deploy', function() { return gulp.src('./build/**/*') .pipe(ghPages()); });
/* * Copyright © 2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import React, { PropTypes } from 'react'; import { connect, Provider } from 'react-redux'; import PluginArtifactUploadStore from 'services/WizardStores/PluginArtifactUpload/PluginArtifactUploadStore'; import PluginArtifactUploadActions from 'services/WizardStores/PluginArtifactUpload/PluginArtifactUploadActions'; import T from 'i18n-react'; import FileDnD from 'components/FileDnD'; require('./UploadJarStep.scss'); const mapStateWithDNDFileProps = (state) => { return { file: state.upload.jar.contents, error: state.upload.jar.__error }; }; const mapDispatchWithDNDFileProps = (dispatch) => { return { onDropHandler: (e) => { dispatch({ type: PluginArtifactUploadActions.setFilePath, payload: { file: e[0] } }); } }; }; const ArtifactUploader = connect( mapStateWithDNDFileProps, mapDispatchWithDNDFileProps )(FileDnD); export default function UploadJarStep(undefined, context) { return ( <Provider store={PluginArtifactUploadStore}> <div className="upload-step-container"> { context.isMarket ? ( <h4 className="upload-instruction"> {T.translate('features.Wizard.ArtifactUpload.Step1.uploadHelperText')} </h4> ) : null } <ArtifactUploader /> </div> </Provider> ); } UploadJarStep.contextTypes = { isMarket: PropTypes.bool };
/* * watch-test.js: Tests for restarting forever processes when a file changes. * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ var assert = require('assert'), path = require('path'), fs = require('fs'), vows = require('vows'), forever = require('../../lib/forever'); vows.describe('forever/monitor/watch').addBatch({ 'When using forever with watch enabled': { 'forever should': { topic: forever.start('daemon.js', { silent: true, options: ['-p', '8090'], watch: true, sourceDir: path.join(__dirname, '..', 'fixtures', 'watch') }), 'have correct options set': function (child) { assert.isTrue(child.watchIgnoreDotFiles); assert.equal(fs.realpathSync(path.join(__dirname, '..', 'fixtures', 'watch')), fs.realpathSync(child.watchDirectory)); }, 'when file changes': { topic: function (child) { child.once('restart', this.callback); fs.writeFileSync(path.join(__dirname, '..', 'fixtures', 'watch', 'file'), '// hello, I know nodejitsu.'); }, 'restart the script': function (child, _) { fs.writeFileSync(path.join(__dirname, '..', 'fixtures', 'watch', 'file'), '/* hello, I know nodejitsu. */'); } }, 'when file is added': { topic: function (child) { child.once('restart', this.callback); fs.writeFileSync(path.join(__dirname, '..', 'fixtures', 'watch', 'newFile'), ''); }, 'restart the script': function (child, _) { fs.unlinkSync(path.join(__dirname, '..', 'fixtures', 'watch', 'newFile')); } }, 'when file is removed': { topic: function (child) { child.once('restart', this.callback); try { fs.unlinkSync(path.join(__dirname, '..', 'fixtures', 'watch', 'removeMe')) } catch (ex) { } }, 'restart the script': function (child, _) { fs.writeFileSync(path.join(__dirname, '..', 'fixtures', 'watch', 'removeMe'), ''); } }, 'read .foreverignore file': { 'and store ignore patterns': function (child) { assert.deepEqual( child.watchIgnorePatterns, fs.readFileSync( path.join(__dirname, '..', 'fixtures', 'watch', '.foreverignore'), 'utf8' ).split("\n") ); } } } } }).export(module);
const fs = require("fs"); const axios = require("axios"); const BLIZZARD_URL = "https://eu.battle.net/oauth/token"; // Create axios interceptor that on Authorization will refresh the access token const connection = axios.create(); connection.interceptors.response.use( (res) => { return res; }, async (err) => { // Important! If current token is expired/wrong remove it from the headers if (err.response.data.error === "invalid_token") { delete connection.defaults.headers["Authorization"]; delete err.response.config.headers["Authorization"]; } // On authorization error, retrieve an access token from the Blizzard API if (err.response.status === 401) { return connection .post( BLIZZARD_URL, {}, { params: { grant_type: "client_credentials", client_id: process.env.BLIZZARD_CLIENT, client_secret: process.env.BLIZZARD_SECRET, }, } ) .then(({ data }) => { connection.defaults.headers[ "Authorization" ] = `Bearer ${data.access_token}`; err.response.config.headers[ "Authorization" ] = `Bearer ${data.access_token}`; return connection(err.response.config); }) .catch((err) => Promise.reject(err)); } return Promise.reject(err); } ); // Fetch wow token price from set regions and save it as a JSON file exports.tokenPrice = async () => { const regions = ["eu", "us", "kr", "tw"]; const tokens = { regions: {}, last_update: 0 }; for (const region of regions) { await connection .get( `https://${region}.api.blizzard.com/data/wow/token/index?namespace=dynamic-${region}` ) .then(({ data }) => { tokens.regions[region] = data.price / 10000; }) .finally(() => { tokens.last_update = new Date().getTime(); }) .catch((err) => console.error(err.response.data)); } await fs.promises.writeFile( "data/wowtoken-data.json", JSON.stringify(tokens), (err) => { if (err) throw err; } ); }; // Fetch character profile avatar's URL // example URL: https://render.worldofwarcraft.com/eu/character/xxx/xxx/xxx-inset.jpg const characterAvatar = async (region, realmSlug, characterName) => { return await connection .get( `https://${region}.api.blizzard.com/profile/wow/character/${realmSlug}/${characterName}/character-media?namespace=profile-${region}` ) .then(({ data }) => { return data.assets[1].value; }) .catch((err) => console.error(err.response.data)); }; // Destructure character's profile data const character = async ( characterData, { region, realmSlug, characterName } ) => { const { name, realm, level, faction, guild, character_class, race, covenant_progress, active_spec, average_item_level, equipped_item_level, achievement_points, } = characterData; return { name: name, realm: realm.name.en_GB, level: level, faction: faction?.name.en_GB, guild: guild?.name, class: character_class?.name.en_GB, race: race.name.en_GB, covenant: { name: covenant_progress?.chosen_covenant.name.en_GB, renown: covenant_progress?.renown_level, }, spec: active_spec?.name.en_GB, ilvl: { avg: average_item_level, eq: equipped_item_level, }, achiev_points: achievement_points, image: await characterAvatar(region, realmSlug, characterName), }; }; // Fetch character's profile data exports.characterInfo = async (region, realmSlug, characterName) => { return await connection .get( `https://${region}.api.blizzard.com/profile/wow/character/${realmSlug}/${characterName}?namespace=profile-${region}` ) .then(({ data }) => { return character(data, { region, realmSlug, characterName, }); }) .catch((err) => console.error(err.response.data)); };
import { md5 } from './md5'
function addWidgetsfrmCal() { var label121049260345 = new kony.ui.Label({ "id": "label121049260345", "isVisible": true, "skin": "lblSub", "text": "Default view" }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [6, 6, 6, 6], "marginInPixel": true, "padding": [6, 10, 6, 10], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, { "textCopyable": false, "wrapping": constants.WIDGET_TEXT_WORD_WRAP }); var calendar118082077329776 = new kony.ui.Calendar({ "dateFormat": "dd/MM/yyyy", "focusSkin": "calFocus", "id": "calendar118082077329776", "isVisible": true, "skin": "calNormal", "viewConfig": { "gridConfig": { "allowWeekendSelectable": true } }, "viewType": constants.CALENDAR_VIEW_TYPE_DEFAULT }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [12, 4, 12, 4], "marginInPixel": true, "padding": [0, 0, 0, 0], "paddingInPixel": false, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_CENTER }, { "mode": constants.CALENDAR_WHEEL_ONLY_DATE }); var label121049260346 = new kony.ui.Label({ "id": "label121049260346", "isVisible": true, "skin": "lblSub", "text": "GridOnScreen view" }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [6, 6, 6, 6], "marginInPixel": true, "padding": [6, 10, 6, 10], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, { "textCopyable": false, "wrapping": constants.WIDGET_TEXT_WORD_WRAP }); var calendar118082077329786 = new kony.ui.Calendar({ "dateFormat": "dd/MM/yyyy", "focusSkin": "calFocus", "id": "calendar118082077329786", "isVisible": true, "skin": "calNormal", "viewConfig": { "gridConfig": { "allowWeekendSelectable": true } }, "viewType": constants.CALENDAR_VIEW_TYPE_GRID_ONSCREEN }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [12, 4, 12, 4], "marginInPixel": true, "padding": [0, 0, 0, 0], "paddingInPixel": false, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_CENTER }, { "containerHeightReference": constants.CONTAINER_HEIGHT_BY_FORM_REFERENCE, "data": {}, "dayTextAlignmentInCell": constants.CONTENT_ALIGN_CENTER, "mode": constants.CALENDAR_WHEEL_ONLY_DATE }); var label118082077329800 = new kony.ui.Label({ "id": "label118082077329800", "isVisible": true, "skin": "lblSub", "text": "GridPopup view" }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [6, 6, 6, 6], "marginInPixel": true, "padding": [6, 10, 6, 10], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, { "textCopyable": false, "wrapping": constants.WIDGET_TEXT_WORD_WRAP }); var calendar118082077329814 = new kony.ui.Calendar({ "dateFormat": "dd/MM/yyyy", "focusSkin": "calFocus", "id": "calendar118082077329814", "isVisible": true, "skin": "calNormal", "viewConfig": { "gridConfig": { "allowWeekendSelectable": true } }, "viewType": constants.CALENDAR_VIEW_TYPE_GRID_POPUP }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [12, 4, 12, 4], "marginInPixel": true, "padding": [0, 0, 0, 0], "paddingInPixel": false, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_CENTER }, { "containerHeightReference": constants.CONTAINER_HEIGHT_BY_FORM_REFERENCE, "data": {}, "dayTextAlignmentInCell": constants.CONTENT_ALIGN_CENTER, "mode": constants.CALENDAR_WHEEL_ONLY_DATE }); var label118082077329845 = new kony.ui.Label({ "id": "label118082077329845", "isVisible": true, "skin": "lblSub", "text": "WheelOnScreen view" }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [6, 6, 6, 6], "marginInPixel": true, "padding": [6, 10, 6, 10], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, { "textCopyable": false, "wrapping": constants.WIDGET_TEXT_WORD_WRAP }); var calendar118082077329855 = new kony.ui.Calendar({ "dateFormat": "dd/MM/yyyy", "focusSkin": "calFocus", "id": "calendar118082077329855", "isVisible": true, "skin": "calNormal", "viewConfig": { "gridConfig": { "allowWeekendSelectable": true } }, "viewType": constants.CALENDAR_VIEW_TYPE_WHEEL_ONSCREEN }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [12, 4, 12, 4], "marginInPixel": true, "padding": [0, 0, 0, 0], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_CENTER }, { "mode": constants.CALENDAR_WHEEL_ONLY_DATE }); var label118082077329869 = new kony.ui.Label({ "id": "label118082077329869", "isVisible": true, "skin": "lblSub", "text": "WheelPopup view" }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [6, 6, 6, 6], "marginInPixel": true, "padding": [6, 10, 6, 10], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, { "textCopyable": false, "wrapping": constants.WIDGET_TEXT_WORD_WRAP }); var calendar118082077329879 = new kony.ui.Calendar({ "dateFormat": "dd/MM/yyyy", "focusSkin": "calFocus", "id": "calendar118082077329879", "isVisible": true, "skin": "calNormal", "viewConfig": { "gridConfig": { "allowWeekendSelectable": true } }, "viewType": constants.CALENDAR_VIEW_TYPE_WHEEL_POPUP }, { "containerWeight": 100, "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT, "hExpand": true, "margin": [12, 4, 12, 4], "marginInPixel": true, "padding": [0, 0, 0, 0], "paddingInPixel": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_CENTER }, { "mode": constants.CALENDAR_WHEEL_ONLY_DATE }); frmCal.add(label121049260345, calendar118082077329776, label121049260346, calendar118082077329786, label118082077329800, calendar118082077329814, label118082077329845, calendar118082077329855, label118082077329869, calendar118082077329879); }; function frmCalGlobals() { frmCal = new kony.ui.Form2({ "addWidgets": addWidgetsfrmCal, "bounces": true, "enabledForIdleTimeout": false, "id": "frmCal", "needAppMenu": true, "skin": "frm", "title": "Calender" }, { "displayOrientation": constants.FORM_DISPLAY_ORIENTATION_PORTRAIT, "layoutType": constants.CONTAINER_LAYOUT_BOX, "paddingInPixel": false }, { "bounces": true, "configureExtendBottom": false, "configureExtendTop": false, "configureStatusBarStyle": false, "extendBottom": false, "extendTop": false, "footerOverlap": false, "formTransparencyDuringPostShow": 100, "headerOverlap": false, "inputAccessoryViewType": constants.FORM_INPUTACCESSORYVIEW_DEFAULT, "inTransitionConfig": { "transitionDirection": "none", "transitionEffect": "none" }, "needsIndicatorDuringPostShow": true, "outTransitionConfig": { "transitionDirection": "none", "transitionEffect": "none" }, "retainScrollPosition": false, "statusBarStyle": constants.STATUS_BAR_STYLE_DEFAULT, "titleBar": true, "titleBarConfig": { "renderTitleText": true, "prevFormTitle": false, "titleBarLeftSideView": "title", "labelLeftSideView": "Back", "titleBarRightSideView": "none" }, "titleBarSkin": "sknTitleBarSampleApp" }); frmCal.info = { "kuid": "p2kwiet1288931495524" }; };
/* @flow */ import EventEmitter from 'events'; import crypto from 'crypto'; import warning from 'warning'; import { LineClient } from 'messaging-api-line'; import LineContext from '../context/LineContext'; import LineEvent, { type LineRawEvent } from '../context/LineEvent'; import { type Session } from '../session/Session'; import { type Connector } from './Connector'; type LineRequestBody = { destination: string, events: Array<LineRawEvent>, }; type ConstructorOptions = {| accessToken?: string, channelSecret?: string, client?: LineClient, mapDestinationToAccessToken?: (destination: string) => Promise<string>, shouldBatch: ?boolean, sendMethod: ?string, origin?: string, skipProfile?: ?boolean, |}; export default class LineConnector implements Connector<LineRequestBody> { _client: LineClient; _channelSecret: string; _skipProfile: boolean; _mapDestinationToAccessToken: ?(destination: string) => Promise<string>; _shouldBatch: ?boolean; _sendMethod: ?string; constructor({ accessToken, channelSecret, client, mapDestinationToAccessToken, shouldBatch, sendMethod, origin, skipProfile, }: ConstructorOptions) { this._client = client || LineClient.connect({ accessToken, origin, }); this._channelSecret = channelSecret || ''; this._mapDestinationToAccessToken = mapDestinationToAccessToken; this._shouldBatch = shouldBatch || false; warning( !sendMethod || sendMethod === 'reply' || sendMethod === 'push', 'sendMethod should be one of `reply` or `push`' ); this._sendMethod = sendMethod || 'push'; // FIXME: maybe set this default value as true this._skipProfile = typeof skipProfile === 'boolean' ? skipProfile : false; } _isWebhookVerifyEvent(event: LineRawEvent): boolean { return ( event.replyToken === '00000000000000000000000000000000' || event.replyToken === 'ffffffffffffffffffffffffffffffff' ); } isWebhookVerifyRequest(body: LineRequestBody): boolean { return ( body && Array.isArray(body.events) && body.events.length > 0 && body.events.every(this._isWebhookVerifyEvent) ); } get platform(): string { return 'line'; } get client(): LineClient { return this._client; } getUniqueSessionKey(body: LineRequestBody): string { const { source } = body.events[0]; if (source.type === 'user') { return source.userId; } if (source.type === 'group') { return source.groupId; } if (source.type === 'room') { return source.roomId; } throw new TypeError( 'LineConnector: sender type should be one of user, group, room.' ); } async updateSession(session: Session, body: LineRequestBody): Promise<void> { const { source } = body.events[0]; if (!session.type) { session.type = source.type; } if (source.type === 'group') { let user = null; if (source.userId) { user = this._skipProfile ? { id: source.userId, _updatedAt: new Date().toISOString(), } : { id: source.userId, _updatedAt: new Date().toISOString(), ...(await this._client.getGroupMemberProfile( source.groupId, source.userId )), }; } session.user = user; let memberIds = []; try { memberIds = await this._client.getAllGroupMemberIds(source.groupId); } catch (e) { // FIXME: handle no memberIds // only LINE@ Approved accounts or official accounts can use this API // https://developers.line.me/en/docs/messaging-api/reference/#get-group-member-user-ids } session.group = { id: source.groupId, members: memberIds.map(id => ({ id })), _updatedAt: new Date().toISOString(), }; } else if (source.type === 'room') { let user = null; if (source.userId) { user = this._skipProfile ? { id: source.userId, _updatedAt: new Date().toISOString(), } : { id: source.userId, _updatedAt: new Date().toISOString(), ...(await this._client.getRoomMemberProfile( source.roomId, source.userId )), }; } session.user = user; let memberIds = []; try { memberIds = await this._client.getAllRoomMemberIds(source.roomId); } catch (e) { // FIXME: handle no memberIds // only LINE@ Approved accounts or official accounts can use this API // https://developers.line.me/en/docs/messaging-api/reference/#get-room-member-user-ids } session.room = { id: source.roomId, members: memberIds.map(id => ({ id })), _updatedAt: new Date().toISOString(), }; } else if (source.type === 'user') { if (!session.user) { const user = this._skipProfile ? {} : await this._client.getUserProfile(source.userId); session.user = { id: source.userId, _updatedAt: new Date().toISOString(), ...user, }; } } if (session.group) { Object.freeze(session.group); } Object.defineProperty(session, 'group', { configurable: false, enumerable: true, writable: false, value: session.group, }); if (session.room) { Object.freeze(session.room); } Object.defineProperty(session, 'room', { configurable: false, enumerable: true, writable: false, value: session.room, }); if (session.user) { Object.freeze(session.user); } Object.defineProperty(session, 'user', { configurable: false, enumerable: true, writable: false, value: session.user, }); } mapRequestToEvents(body: LineRequestBody): Array<LineEvent> { const { destination } = body; return body.events .filter(event => !this._isWebhookVerifyEvent(event)) .map(event => new LineEvent(event, { destination })); } async createContext(params: { event: LineEvent, session: ?Session, initialState: ?Object, requestContext: ?Object, emitter?: ?EventEmitter, }): Promise<LineContext> { let customAccessToken; if (this._mapDestinationToAccessToken) { const { destination } = params.event; if (!destination) { warning(false, 'Could not find destination from request body.'); } else { customAccessToken = await this._mapDestinationToAccessToken( destination ); } } return new LineContext({ ...params, client: this._client, customAccessToken, shouldBatch: this._shouldBatch, sendMethod: this._sendMethod, }); } verifySignature(rawBody: string, signature: string): boolean { const hashBufferFromBody = crypto .createHmac('sha256', this._channelSecret) .update(rawBody, 'utf8') .digest(); const bufferFromSignature = Buffer.from(signature, 'base64'); // return early here if buffer lengths are not equal since timingSafeEqual // will throw if buffer lengths are not equal if (bufferFromSignature.length !== hashBufferFromBody.length) { return false; } return crypto.timingSafeEqual(bufferFromSignature, hashBufferFromBody); } }
module.exports = { plugins: [ { resolve: "gatsby-plugin-antd", options: { style: true } }, { resolve: "gatsby-plugin-less", options: { javascriptEnabled: true, modifyVars: { "primary-color": "#26475F", "link-color": "#0088B7" } } } ] };
const util = require("util"); const fs = require("fs"); const sharp = require("sharp"); const { isInt, uploadFile, deleteFile } = require("./helpers"); const unlinkFile = util.promisify(fs.unlink); const getUserStars = async (req, res) => { if (!isInt(req.params.userId)) { res.status(400).end(); return; } const { userId } = req.params; const starInstance = await req.app.locals.db.Stars.findAll({ where: { userId }, }); if (starInstance === null) { res.status(200).json([]); } else { const starredDropsInstances = starInstance.map(async (star) => { const dropInstance = await req.app.locals.db.Drops.findOne({ where: { id: star.dataValues.dropId }, attributes: ["id", "title", "description", "lang"], }); return dropInstance.dataValues; }); res.status(200).json(starredDropsInstances); } }; const getUserProfile = async (req, res) => { if (!isInt(req.params.userId)) { res.status(400).end(); return; } const userId = parseInt(req.params.userId, 10); try { const userInstance = await req.app.locals.db.Users.findByPk(userId, { attributes: [ "id", "username", "description", "avatar", "numStars", "numForks", ], }); // console.log("User model is", userModel); if (userInstance === null) { res.status(404).end(); return; } let userDrops; let languageCount; // If the current user is requesting their profile, return private drops as well if (req.user !== undefined && req.user.uid === userId) { userDrops = await req.app.locals.db.Drops.findAll({ where: { userId }, attributes: ["id", "title", "lang", "userId"], }); languageCount = await req.app.locals.db.Drops.findAll({ where: { userId }, group: ["drops.lang"], attributes: [ "lang", [ req.app.locals.db.sequelize.fn( "count", req.app.locals.db.sequelize.col("lang") ), "count", ], ], }); } else { userDrops = await req.app.locals.db.Drops.findAll({ where: { userId, visibility: true }, attributes: ["id", "title", "lang", "userId"], }); languageCount = await req.app.locals.db.Drops.findAll({ where: { userId, visibility: true }, group: ["drops.lang"], attributes: [ "lang", [ req.app.locals.db.sequelize.fn( "count", req.app.locals.db.sequelize.col("lang") ), "count", ], ], }); } res.status(200).json({ profile: userInstance.dataValues, drops: userDrops || [], counts: languageCount || [], }); } catch (err) { res.status(500).end(); } }; const updateUserProfile = async (req, res) => { if (!isInt(req.params.userId)) { res.status(400).end(); } else if ( req.user === undefined || req.user.uid !== parseInt(req.params.userId, 10) ) { res.status(401).end(); return; } else if ( req.body.description === undefined || req.body.description.length === 0 ) { res.status(400).end(); return; } const { userId } = req.params; const { description } = req.body; const userInstance = await req.app.locals.db.Users.findByPk(userId); if (userInstance === null) { res.status(404).end(); } else { userInstance.description = description; await userInstance.save(); res.status(200).end(); } }; const deleteUser = async (req, res) => { if (!isInt(req.params.userId)) { res.status(400).end(); return; } if ( req.user === undefined || req.user.uid !== parseInt(req.params.userId, 10) ) { res.status(401).end(); return; } const userId = parseInt(req.params.userId, 10); try { const userInstance = await req.app.locals.db.Users.findByPk(userId); if (userInstance === null) { res.status(404).end(); } else { await userInstance.destroy(); req.logout(); res.status(200).end(); } } catch { res.status(500).end(); } }; const updateAvatar = async (req, res) => { if (!isInt(req.params.userId)) { res.status(400).end(); return; } if ( req.user === undefined || req.user.uid !== parseInt(req.params.userId, 10) ) { res.status(401).end(); return; } const userId = parseInt(req.params.userId, 10); const uploadedFile = req.file; console.log("File", uploadedFile); try { if ( uploadedFile.mimetype !== "image/png" && uploadedFile.mimetype !== "image/jpg" && uploadedFile.mimetype !== "image/jpeg" ) { await unlinkFile(uploadedFile.path); res.status(400).end(); return; } const userInstance = await req.app.locals.db.Users.findByPk(userId); if (userInstance === null) { res.status(404).end(); return; } const resizedAvatarFilePath = `${uploadedFile.path}.${ uploadedFile.mimetype.split("/")[1] }`; const resizedAvatarFileName = `${uploadedFile.filename}.${ uploadedFile.mimetype.split("/")[1] }`; await sharp(uploadedFile.path) .resize(400, 500, { fit: "fill" }) .png() .toFile(resizedAvatarFilePath); await unlinkFile(uploadedFile.path); const result = await uploadFile( resizedAvatarFilePath, resizedAvatarFileName ); if (result !== null) { if (userInstance.dataValues.avatarKey !== null) { await deleteFile(userInstance.dataValues.avatarKey); } await unlinkFile(resizedAvatarFilePath); // Update values for new avatar userInstance.avatar = result.Location; userInstance.avatarKey = result.Key; await userInstance.save(); res.send({ avatarURL: result.Location }); return; } res.status(400).end(); // res.status(200).end(); } catch { res.status(500).end(); } }; module.exports = { deleteUser, updateUserProfile, getUserProfile, getUserStars, updateAvatar, };
var error = require('../../serror') var res = require('../../res'); var protocol = require('../../../network/protocol'); var nodes = require('../../../db/entity/network/nodes') module.exports = function (params) { var peers = protocol.getNodeList(), peerinfo = {}; for (var i in peers) { var d = nodes.get("data/" + peers[i]); var rinfo = protocol.getUniqAddress(peers[i]); if (rinfo.remoteAddress == '127.0.0.1') continue; d.lastMsg = new Date().getTime() / 1000 - d.lastRecv; peerinfo[rinfo.remoteAddress + "//" + rinfo.port] = d; } return res(peerinfo); }
// No need for this now, update next time const uploadElements = { chooseUploadListing: '//*[@id="ngf-label-upload-button-listing"]/input[@id="ngf-upload-button-listing"]', uploadButton: '.btn.btn-ai-success', listingUploadText: '//chpl-upload/div/div/chpl-upload-listings/div/div[2]/div', uploadSuccessfulText: '//*[@id="main-content"]/div/ui-view/chpl-upload/div/div/chpl-upload-listings/div/div[2]/div', }; const path = require('path'); class UploadPage { constructor () { } get chooseUploadListingButton () { return $(uploadElements.chooseUploadListing); } get uploadButton () { return $(uploadElements.uploadButton); } get uploadSuccessfulText () { return $(uploadElements.uploadSuccessfulText); } get listingUploadText () { return $(uploadElements.listingUploadText); } waitForSuccessfulUpload (fileName) { browser.waitUntil( () => this.uploadSuccessfulText.getText().includes(fileName)); } uploadListing (uploadfilePath) { const filePath = path.join(__dirname, uploadfilePath); this.chooseUploadListingButton.addValue(browser.uploadFile(filePath)); this.uploadButton.waitAndClick(); browser.waitUntil( () => this.listingUploadText.isDisplayed()); } } export default UploadPage;
macDetailCallback("6c0b84000000/24",[{"d":"2014-07-29","t":"add","a":"141, Lane 351, TaiPing Road, Sec.1\nTsao-Tuen Nan-Tou 54261\n\n","c":"TAIWAN, PROVINCE OF CHINA","o":"Universal Global Scientific Industrial Co.,Ltd."},{"d":"2015-08-27","t":"change","a":"141, Lane 351, TaiPing Road, Sec.1\nTsao-Tuen Nan-Tou 54261\n\n","c":"TW","o":"Universal Global Scientific Industrial Co.,Ltd."},{"d":"2016-04-09","t":"change","a":"141, Lane 351, TaiPing Road, Sec.1 Tsao-Tuen Nan-Tou TW 54261","c":"TW","o":"Universal Global Scientific Industrial Co., Ltd."}]);
/* * @flow strict-local * Copyright (C) 2020 MetaBrainz Foundation * * This file is part of MusicBrainz, the open internet music database, * and is licensed under the GPL version 2, or (at your option) any * later version: http://www.gnu.org/licenses/gpl-2.0.txt */ import * as React from 'react'; import bugTrackerURL from '../../static/scripts/common/utility/bugTrackerURL'; import ErrorLayout from './ErrorLayout'; import ErrorEnvironment from './components/ErrorEnvironment'; import ErrorInfo from './components/ErrorInfo'; type Props = { +$c: CatalystContextT, +message?: string, +useLanguages: boolean, }; const Error400 = ({ $c, message, useLanguages, }: Props): React.Element<typeof ErrorLayout> => ( <ErrorLayout title={l('Bad Request')}> <p> <strong> {l('Sorry, there was a problem with your request.')} </strong> </p> <ErrorInfo message={message} /> <p> {exp.l( 'Looking for help? Check out our {doc|documentation} or {faq|FAQ}.', {doc: '/doc/MusicBrainz_Documentation', faq: '/doc/FAQ'}, )} </p> <p> {exp.l( `Found a problem on our site? Please {report|report a bug} and include any error message that is shown above.`, { report: bugTrackerURL(), }, )} </p> <h2>{l('Technical Information')}</h2> <ErrorEnvironment $c={$c} useLanguages={useLanguages} /> </ErrorLayout> ); export default Error400;
//Script copyright (c) 2005 BR Fletcher & R Williams //Portions of the code in this file are from www.quirksmode.org //BUILD 8/12/2005 11:18AM /*onscreen, */ /*the valid vertical positions for notes. element 0 is top G, element 1 is F below top G. This is used to lock the notes to the nearest line or space in the staff.*/ var validPositionsY = new Array( 32 + 20, 44 + 20, 56 + 20, 68 + 20, 80 + 20, 92 + 20, 104 + 20, 116 + 20, 128 + 20, 140 + 20, 152 + 20, 164 + 20, 176 + 20, 188 + 20, 200 + 20, 212 + 20, 224 + 20, 236 + 20, 248 + 20, 260 + 20, 272 + 20, 284 + 20, 296 + 20); // var pitches = new Array(19, 17, 16, 14, 12, 11, 9, 7, 5, 4, 2, 0, -1, -3, -5, -7, -8, -10, -12, -13, -15, -17, -19); /*the valid horizontal positions for notes. element 0 is chord one, element 1 is chord 2. This is used to lock the notes to the nearest chord.*/ var validPositionsX = new Array(348, 470); /*these are the vertical positions of the different sharps for the keysignature in the treble clef.*/ var sharpHeights = new Array(1 + 20, 38 + 20, 0, 25 + 20, 62 + 20, 14 + 20, 49 + 20); /*these are the vertical positions of the different sharps for the keysignature in the bass clef.*/ var sharpHeights2 = new Array(213 - 23, 250 - 23, 202 - 23, 237 - 23, 274 - 23, 226 - 23, 261 - 23); /*these are the horizonal positions of the different sharps for the keysignature for both clefs at once. both the treble and bass horizontal positions are the same.*/ var sharpLefts = new Array(130, 160, 185, 210, 235, 260, 285); /*these are the vertical positions of the different flats for the keysignature in the treble clef.*/ var flatHeights = new Array(49 + 20, 14 + 20, 62 + 20, 25 + 20, 73 + 20, 38 + 20, 86 + 20); /*these are the vertical positions of the different flatss for the keysignature in the bass clef.*/ var flatHeights2 = new Array(261 - 23, 226 - 23, 274 - 23, 237 - 23, 285 - 23, 250 - 23, 297 - 23); /*these are the horizonal positions of the different flats for the keysignature for both clefs at once. both the treble and bass horizontal positions are the same.*/ var flatLefts = new Array(130, 160, 185, 210, 235, 260, 285); /*place the flats keysignature on the web page based on `keysig`. This does both treble and bass clef.*/ function placeFlats(keysig) { /*the first `if` is used as an example. if `keysig`.b (b is the first flat), is flat, make the treble claf B flat visible, and the bass claf B flat visible.*/ if(keysig.b == -1) { get('flats0').style.display = 'block'; get('flats20').style.display = 'block'; } if(keysig.e == -1) { get('flats1').style.display = 'block'; get('flats21').style.display = 'block'; } if(keysig.a == -1) { get('flats2').style.display = 'block'; get('flats22').style.display = 'block'; } if(keysig.d == -1) { get('flats3').style.display = 'block'; get('flats23').style.display = 'block'; } if(keysig.g == -1) { get('flats4').style.display = 'block'; get('flats24').style.display = 'block'; } if(keysig.c == -1) { get('flats5').style.display = 'block'; get('flats25').style.display = 'block'; } if(keysig.f == -1) { get('flats6').style.display = 'block'; get('flats26').style.display = 'block'; } } /*place the sharps keysignature on the web page based on `keysig`. This does both treble and bass clef.*/ function placeSharps(keysig) { /*the first `if` is used as an example. if `keysig`.f (f is the first sharp), is sharp, make the treble claf F sharp visible, and the bass claf F sharp visible.*/ if(keysig.f == 1) { get('sharps0').style.display = 'block'; get('sharps20').style.display = 'block'; } if(keysig.c == 1) { get('sharps1').style.display = 'block'; get('sharps21').style.display = 'block'; } if(keysig.g == 1) { get('sharps2').style.display = 'block'; get('sharps22').style.display = 'block'; } if(keysig.d == 1) { get('sharps3').style.display = 'block'; get('sharps23').style.display = 'block'; } if(keysig.a == 1) { get('sharps4').style.display = 'block'; get('sharps24').style.display = 'block'; } if(keysig.e == 1) { get('sharps5').style.display = 'block'; get('sharps25').style.display = 'block'; } if(keysig.b == 1) { get('sharps6').style.display = 'block'; get('sharps26').style.display = 'block'; } } /*given a keysig `keysig`, place the sharos or flats of the keysignature on the web page.*/ function setKeySig(keysig) { /*find the x and y offset of the staff off of the web page.*/ var staffX = findPosX(get('staff')); var staffY = findPosY(get('staff')); /*position each treble clef flat relative to the staff using the positions specified in the arrays at the top of the script and hide the flats.*/ for(var i = 0; i < flatHeights.length; i++) { get('flats' + i).style.left = staffX + flatLefts[i] + 'px'; get('flats' + i).style.top = staffY + flatHeights[i] + 'px'; get('flats' + i).style.display = 'none'; } /*position each bass clef flat relative to the staff using the positions specified in the arrays at the top of the script and hide the flats.*/ for(i = 0; i < flatHeights.length; i++) { get('flats2' + i).style.left = staffX + flatLefts[i] + "px"; get('flats2' + i).style.top = staffY + flatHeights2[i] + "px"; get('flats2' + i).style.display = 'none'; } /*position each treble clef sharp relative to the staff using the positions specified in the arrays at the top of the script and hide the sharp.*/ for(i = 0; i < sharpHeights.length; i++) { get('sharps' + i).style.left = staffX + sharpLefts[i] + "px"; get('sharps' + i).style.top = staffY + sharpHeights[i] + "px"; get('sharps' + i).style.display = 'none'; } /*position each bass clef sharp relative to the staff using the positions specified in the arrays at the top of the script and hide the sharp.*/ for(i = 0; i < sharpHeights.length; i++) { get('sharps2' + i).style.left = staffX + sharpLefts[i] + "px"; get('sharps2' + i).style.top = staffY + sharpHeights2[i] + "px"; get('sharps2' + i).style.display = 'none'; } //if the keysig has at least one flat, place flats if(keysig.f == 1) placeSharps(keysig); //otherwise, if the keysig has at least one sharp, place sharps else if(keysig.b == -1) placeFlats(keysig); } /*place a note `semi` on the staff, given an x and y positon, and a staff x and y offset.*/ function setPos(semi, xPos, yPos, staffX, staffY) { get('semi' + semi + 'con').style.left = (staffX + validPositionsX[xPos]) + "px"; get('semi' + semi + 'con').style.top = (staffY + validPositionsY[yPos]) + "px"; } /*given the name of a note on the web page, find out which chord it belongs to.*/ function getChord(semi) { //get the x offset of the staff on the web page. var staffX = findPosX(get('staff')); /*get the x position of the note, and subtract the staff offset to get the position relative to the staff.*/ var objX = findPosX(semi) - staffX; var chord = 0; for(var i = 0; i < validPositionsX.length; i++) { //if the x position of the note matches one of the valid positions if(validPositionsX[i] == objX) { //the chord is set to the index of the valid positions array chord = i; break; } } return chord; } /*given the name of a note on the web page, find out what it's correct pitch is.*/ function getPitch(semi) { //get the y offset of the staff on the web page. var staffY = findPosY(get('staff')); /*get the y position of the note, and subtract the staff offset to get the position relative to the staff.*/ var objY = findPosY(semi) - staffY; var pitch = 0; for(var i = 0; i < validPositionsY.length; i++) { //if the y position of the note matches one of the valid positions if(validPositionsY[i] == objY) { //the pitch is set to the index of the valid positions array pitch = i; break; } } return pitches[pitch]; } /*given a vertical position, and the offset of the staff, this funtion finds the index into the vertical valid positions array, which is nearest to the position specified.*/ function findValidIndexY(pos, offset) { /*declare the range on either side of `pos` which we will include in our search for the correct index*/ var smallPos = pos - 10, bigPos = pos + 10; var validIndex = 0; var validPos = validPositionsY[validIndex] + offset; //while the current valid position is not in the range (pos - 10, pos + 10) while( !( (smallPos < validPos) && (validPos < bigPos) ) ) { validIndex++; /*if we have checked the entire valid positions array against the input `pos`, return the last index*/ if(validIndex >= validPositionsY.length) return (validIndex - 1); validPos = validPositionsY[validIndex] + offset; } return validIndex; } /*given a horizontal position, and the offset of the staff, this funtion finds the index into the horizontal valid positions array, which is nearest to the position specified.*/ function findValidIndexX(pos, offset) { /*declare the range on either side of `pos` which we will include in our search for the correct index*/ var smallPos = pos - 60, bigPos = pos + 60; var validIndex = 0; var validPos = validPositionsX[validIndex] + offset; //while the current valid position is not in the range (pos - 60, pos + 60) while( !( (smallPos < validPos) && (validPos < bigPos) ) ) { validIndex++; /*if we have checked the entire valid positions array against the input `pos`, return the last index*/ if(validIndex >= validPositionsX.length) return (validIndex - 1); validPos = validPositionsX[validIndex] + offset; } return validIndex; } //The following portion of code is used from quirksmode.org //find the x position of an element on a web page. function findPosX(obj) { var curleft = 0; if(obj.offsetParent) { while(obj.offsetParent) { curleft += obj.offsetLeft; obj = obj.offsetParent; } } else if(obj.x) curleft += obj.x; return curleft; } //find the y position of an element on a web page. function findPosY(obj) { var curtop = 0; if(obj.offsetParent) { while(obj.offsetParent) { curtop += obj.offsetTop; obj = obj.offsetParent; } } else if(obj.y) curtop += obj.y; return curtop; } //end portion //used in an array sort function compareNumbers(a, b) { return b - a; } //This function initializes chord1 and chord2 with their proper notes // based on what notes the users has selected using the graphical interface function setNotesOfChords(chord1, chord2, keysig) { var output = ""; //get the pitches of the 8 note on the web page var pitches = new Array( getPitch(get('semi1con')), getPitch(get('semi2con')), getPitch(get('semi3con')), getPitch(get('semi4con')), getPitch(get('semi5con')), getPitch(get('semi6con')), getPitch(get('semi7con')), getPitch(get('semi8con'))); //get what chords the eight notes on the web page belong to var chords = new Array( getChord(get('semi1con')), getChord(get('semi2con')), getChord(get('semi3con')), getChord(get('semi4con')), getChord(get('semi5con')), getChord(get('semi6con')), getChord(get('semi7con')), getChord(get('semi8con'))); //2 arrays, 1 for each chord var chord1Pitches = new Array(); var chord2Pitches = new Array(); //place notes into the chord pitches array based on the `chords` array for(var i = 0; i < pitches.length; i++) { if(chords[i] == 0) chord1Pitches.push(pitches[i]); else chord2Pitches.push(pitches[i]); } //sort the pitches in descending order chord1Pitches.sort(compareNumbers); chord2Pitches.sort(compareNumbers); // check that there are 4 elements in both chord pitches arrays if(chord1Pitches.length < 4) output = output + "There aren't enough notes in chord 1.\n"; if(chord1Pitches.length > 4) output = output + "There are too many notes in chord 1.\n"; if(chord2Pitches.length < 4) output = output + "There aren't enough notes in chord 2.\n"; if(chord2Pitches.length > 4) output = output + "There are too many notes in chord 2.\n"; /*alter the values of `chord1Pitches` using any accidentals for that note, and the keysignature. Place the result into the correct part of the chird1 variable.*/ chord1.s = convertAccKeySig(chord1Pitches[0] + 60, get('acc1i').value, keysig); chord1.a = convertAccKeySig(chord1Pitches[1] + 60, get('acc2i').value, keysig); chord1.t = convertAccKeySig(chord1Pitches[2] + 60, get('acc3i').value, keysig); chord1.b = convertAccKeySig(chord1Pitches[3] + 60, get('acc4i').value, keysig); /*alter the values of `chord2Pitches` using any accidentals for that note, and the keysignature. Place the result into the correct part of the chird1 variable.*/ chord2.s = convertAccKeySig(chord2Pitches[0] + 60, get('acc5i').value, keysig); chord2.a = convertAccKeySig(chord2Pitches[1] + 60, get('acc6i').value, keysig); chord2.t = convertAccKeySig(chord2Pitches[2] + 60, get('acc7i').value, keysig); chord2.b = convertAccKeySig(chord2Pitches[3] + 60, get('acc8i').value, keysig); return output; } /*complete initialization of a chord. This function initialises the triad parts of a chord. It also initializes the name and inversion of the chord off the web page. */ function CIC(chord, keysig, whichChord) { /*intialise the name and inversion of the chord using the input gathered by the webpage from the user.*/ var temp = get('D' + whichChord).value + get('D' + (whichChord + 1)).value; //input into the chord the name and inversion var outChord = createInputChord(chord.b, chord.t, chord.a, chord.s, temp); //initialize the triad parts of the chord outChord.triad = getTriad(keysig, outChord.id, outChord.inv); outChord.setTriad = fixTriad(outChord.triad); return outChord; } /*this variable is used to indicate wether we are in note-raising mode or not. See action1 for more information.*/ var raiseMode = 0; function setRaise() { raiseMode = 1; } /*this variable is shared between 2 functions. When a user wants to move a note, they click the note [triggers action1]. The user then clicks where they want the note to go [triggers secondAction].*/ var sb = null; /*this function is attached by an onclick event to each note on the web page. This function operates in two modes. If we are not in note-raising mode, this function saves the note that was clicked into the sb variable. If we are in note-raising mode, this function class the RaiseSemitone function with the note that was clicked as the argument to thatr function.*/ function action1(e) { /*stop the event from propagating to the staff, because the staff also has an onclick event handler, which we don't want to be called.*/ if(!e) e = window.event; e.cancelBubble = true; if(e.stopPropagation) e.stopPropagation(); //if in raise-mode, raiseSemitone if(raiseMode == 1) { raiseSemitone(this); raiseMode = 0; } else { sb = this; } } /*this function, given a note, raises it by a semitone, and displays the accidental on screen.*/ function raiseSemitone(sb) { //this section of code is the same as the main code that is used to initialise the chord variables //declare chord variables var chord1 = new Chord(0, 0, 0, 0, 0, 0); var chord2 = new Chord(0, 0, 0, 0, 0, 0); //deckare & init keysig var keysig = createKeySignature((get('D70')).options[(get('D70')).selectedIndex].value, get('D71').options[(get('D71')).selectedIndex].value); //if keysig is not valid, alert the user if(keysig == 0) { alert("Please select a valid key signature"); return; } //initialise parts of keysig calcBasedOnTonic(keysig); //initialise chord variables with the croeect notes from the web page var output = setNotesOfChords(chord1, chord2, keysig); //if the output isn't blank (i.e. no errors so far) if(output != "") { //set the output display to the output generated get('S1').value = output; return; } //initialize parts of the chord chord1 = CIC(chord1, keysig, 72); chord2 = CIC(chord2, keysig, 74); //display the keysignature to the user setKeySig(keysig); //end section //get the number of the note gathered var name = (getName(sb)).substring(4, 5); /*this part of the code aplies the keysig to the pitch, because the pitch is not currently uner any keysig.*/ //get the pitch of the gathered note var pitch = getPitch(sb); //temporarily alter the pitch so that it is within an octave of middle C pitch = FO(pitch, 0); /*apply the keysignature to the pitch. based on the pitch of the note, add the keysignature for that note.*/ switch(pitch) { case 0: pitch += keysig.c; break; case 2: pitch += keysig.d; break; case 4: pitch += keysig.e; break; case 5: pitch += keysig.f; break; case 7: pitch += keysig.g; break; case 9: pitch += keysig.a; break; case 11: pitch += keysig.b; break; } /*temporarily alter the pitch for the next bit of code so that it is within an octave of the tonic of the keysignature*/ pitch = FO(pitch, keysig.tonic); //if the key signature is major run fixMajor, otherwise, run fixMinor if(keysig.Type == 1) fixMajor(keysig, name, pitch); else fixMinor(keysig, name, pitch); //move the accidental so that it is next to the note get('acc' + name + 'box').style.left = parseInt(sb.style.left) - 27 + "px"; get('acc' + name + 'box').style.top = parseInt(sb.style.top) - 42 + "px"; //nullify sb so that the accidental won't be applied twice in a row sb = null; } /*This function places an accidental on the webpage for a pitch based on the major keysignature. The name is used to indicate which accidental on the webpage to display.*/ function fixMajor(keysig, name, pitch) { //the first if is used as an example //if the pitch equals the tonic of the key if(pitch == keysig.tonic) { //if the tonic of the key is flattened if(keysig.tonic == -1) { //place a natural accidental get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } //if the tonic of the key is natrual else if(keysig.tonic == 0) { //place a sharp accidental get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } //if the tonic of the key is sharp else { //place a double sharp accidental get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } if(pitch == keysig.tonic + 2) { if(keysig.supt == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.supt == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 4) { if(keysig.medi == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.medi == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 5) { if(keysig.subd == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.subd == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 7) { if(keysig.domi == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.domi == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 9) { if(keysig.subm == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.subm == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 11) { if(keysig.lean == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.lean == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } } /*This function places an accidental on the webpage for a pitch based on the minor keysignature. The name is used to indicate which accidental on the webpage to display.*/ function fixMinor(keysig, name, pitch) { //the first if is used as an example //if the pitch equals the tonic of the key if(pitch == keysig.tonic) { //if the tonic of the key is flattened if(keysig.tonic == -1) { //place a natural accidental get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } //if the tonic of the key is natrual else if(keysig.tonic == 0) { //place a sharp accidental get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } //if the tonic of the key is sharp else { //place a double sharp accidental get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } if(pitch == keysig.tonic + 2) { if(keysig.supt == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.supt == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 3) { if(keysig.medi == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.medi == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 5) { if(keysig.subd == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.subd == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 7) { if(keysig.domi == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.domi == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 8) { if(keysig.subm == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.subm == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } else if(pitch == keysig.tonic + 10) { if(keysig.lean == -1) { get('acc' + name + 'i').value = " "; get('acc' + name + 'box').innerHTML = '<img src="natural.gif">'; } else if(keysig.lean == 0) { get('acc' + name + 'i').value = "#"; get('acc' + name + 'box').innerHTML = '<img src="sharp.gif">'; } else { get('acc' + name + 'i').value = "x"; get('acc' + name + 'box').innerHTML = '<img src="doublesharp.gif">'; } } } //this function is triggered by the user clicking on the staff function secondAction(e) { //if the user hasn't clicked on the note yet, return if(sb == null) return; //the following portion gets the mouse position //The following portion of code is used from quirksmode.org var posx = 0; var posy = 0; if(!e) e = window.event; if(e.pageX || e.pageY) { posx = e.pageX; posy = e.pageY; } else if(e.clientX || e.clientY) { posx = e.clientX + document.body.scrollLeft; posy = e.clientY + document.body.scrollTop; } //end portion //get the horizontal offset of the staff var staffX = findPosX(get('staff')); /*set the position of the note (`sb`) to the nearest valid position. the -17 is used so that the center of the note is used, not the top-left corner.*/ sb.style.left = validPositionsX[findValidIndexX(posx - 17, staffX)] + staffX + "px"; //get the vertical offset of the staff var staffY = findPosY(get('staff')); /*set the position of the note (`sb`) to the nearest valid position. the -11 is used so that the center of the note is used, not the top-left corner.*/ sb.style.top = validPositionsY[findValidIndexY(posy - 11, staffY)] + staffY + "px"; //get the number if this note to use in the next bit of code var name = (getName(sb)).substring(4, 5); //move the accidental for this note number to the correct location/ get('acc' + name + 'box').style.left = parseInt(sb.style.left) - 27 + 'px'; get('acc' + name + 'box').style.top = parseInt(sb.style.top) - 42 + 'px'; //set `sb` to null so that this function isn't called twice in a row by the user sb = null; } /*this function adds the onlick triggers to the notes and to the staff, and sets the initial positions of the notes on the staff.*/ function addMouseOver() { //add the onclick handlers get('staff').onclick = secondAction; get('semi1con').onclick = action1; get('semi2con').onclick = action1; get('semi3con').onclick = action1; get('semi4con').onclick = action1; get('semi5con').onclick = action1; get('semi6con').onclick = action1; get('semi7con').onclick = action1; get('semi8con').onclick = action1; //get offsets of the staff var staffX = findPosX(get('staff')); var staffY = findPosY(get('staff')); //position the notes setPos(1, 0, 0, staffX, staffY); setPos(2, 0, 2, staffX, staffY); setPos(3, 0, 11, staffX, staffY); setPos(4, 0, 18, staffX, staffY); setPos(5, 1, 0, staffX, staffY); setPos(6, 1, 3, staffX, staffY); setPos(7, 1, 12, staffX, staffY); setPos(8, 1, 14, staffX, staffY); } //this function erases all note raising function resetRaise() { //hide all accidentals for(var i = 1; i <= 8; i++) { get('acc' + i + 'i').value = 'none'; get('acc' + i + 'box').innerHTML = ''; } } //repositon the note to make sure it is where it belongs function rePosSB(sb) { //get the current position of `sb` var posx = parseInt(sb.style.left); var posy = parseInt(sb.style.top); //get the x offset of the staff var staffX = findPosX(get('staff')); //set the position of `sb` to the nearest valid x position sb.style.left = validPositionsX[findValidIndexX(posx, staffX)] + staffX + "px"; //get the y offset of the staff var staffY = findPosY(get('staff')); //set the position of `sb` to the nearest valid y position sb.style.top = validPositionsY[findValidIndexY(posy, staffY)] + staffY + "px"; //reposition sb to the new position var name = (getName(sb)).substring(4, 5); get('acc" + name + "box').style.left = parseInt(sb.style.left) - 27 + 'px'; get('acc" + name + "box').style.top = parseInt(sb.style.top) - 42 + 'px'; sb = null; } /*check the positions of the notes and keysignature and reposition them if nessacery. Used for example, if an elemnt on the web page changes size, the staff is moved, and so the notes must be moved as well.*/ function rePosition() { rePosSB(get('semi1con')); rePosSB(get('semi2con')); rePosSB(get('semi3con')); rePosSB(get('semi4con')); rePosSB(get('semi5con')); rePosSB(get('semi6con')); rePosSB(get('semi7con')); rePosSB(get('semi8con')); }
/*! WebUploader 0.1.5 */ /** * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。 * * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。 */ (function( root, factory ) { var modules = {}, // 内部require, 简单不完全实现。 // https://github.com/amdjs/amdjs-api/wiki/require _require = function( deps, callback ) { var args, len, i; // 如果deps不是数组,则直接返回指定module if ( typeof deps === 'string' ) { return getModule( deps ); } else { args = []; for( len = deps.length, i = 0; i < len; i++ ) { args.push( getModule( deps[ i ] ) ); } return callback.apply( null, args ); } }, // 内部define,暂时不支持不指定id. _define = function( id, deps, factory ) { if ( arguments.length === 2 ) { factory = deps; deps = null; } _require( deps || [], function() { setModule( id, factory, arguments ); }); }, // 设置module, 兼容CommonJs写法。 setModule = function( id, factory, args ) { var module = { exports: factory }, returned; if ( typeof factory === 'function' ) { args.length || (args = [ _require, module.exports, module ]); returned = factory.apply( null, args ); returned !== undefined && (module.exports = returned); } modules[ id ] = module.exports; }, // 根据id获取module getModule = function( id ) { var module = modules[ id ] || root[ id ]; if ( !module ) { throw new Error( '`' + id + '` is undefined' ); } return module; }, // 将所有modules,将路径ids装换成对象。 exportsTo = function( obj ) { var key, host, parts, part, last, ucFirst; // make the first character upper case. ucFirst = function( str ) { return str && (str.charAt( 0 ).toUpperCase() + str.substr( 1 )); }; for ( key in modules ) { host = obj; if ( !modules.hasOwnProperty( key ) ) { continue; } parts = key.split('/'); last = ucFirst( parts.pop() ); while( (part = ucFirst( parts.shift() )) ) { host[ part ] = host[ part ] || {}; host = host[ part ]; } host[ last ] = modules[ key ]; } return obj; }, makeExport = function( dollar ) { root.__dollar = dollar; // exports every module. return exportsTo( factory( root, _define, _require ) ); }, origin; if ( typeof module === 'object' && typeof module.exports === 'object' ) { // For CommonJS and CommonJS-like environments where a proper window is present, module.exports = makeExport(); } else if ( typeof define === 'function' && define.amd ) { // Allow using this built library as an AMD module // in another project. That other project will only // see this AMD call, not the internal modules in // the closure below. define([ 'jquery' ], makeExport ); } else { // Browser globals case. Just assign the // result to a property on the global. origin = root.WebUploader; root.WebUploader = makeExport(); root.WebUploader.noConflict = function() { root.WebUploader = origin; }; } })( window, function( window, define, require ) { /** * @fileOverview jQuery or Zepto */ define('dollar-third',[],function() { var $ = window.__dollar || window.jQuery || window.Zepto; if ( !$ ) { throw new Error('jQuery or Zepto not found!'); } return $; }); /** * @fileOverview Dom 操作相关 */ define('dollar',[ 'dollar-third' ], function( _ ) { return _; }); /** * 直接来源于jquery的代码。 * @fileOverview Promise/A+ * @beta */ define('promise-builtin',[ 'dollar' ], function( $ ) { var api; // 简单版Callbacks, 默认memory,可选once. function Callbacks( once ) { var list = [], stack = !once && [], fire = function( data ) { memory = data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ); } firing = false; if ( list ) { if ( stack ) { stack.length && fire( stack.shift() ); } else { list = []; } } }, self = { add: function() { if ( list ) { var start = list.length; (function add ( args ) { $.each( args, function( _, arg ) { var type = $.type( arg ); if ( type === 'function' ) { list.push( arg ); } else if ( arg && arg.length && type !== 'string' ) { add( arg ); } }); })( arguments ); if ( firing ) { firingLength = list.length; } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, disable: function() { list = stack = memory = undefined; return this; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, fireWith: function( context, args ) { if ( list && (!fired || stack) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, fire: function() { self.fireWith( this, arguments ); return this; } }, fired, firing, firingStart, firingLength, firingIndex, memory; return self; } function Deferred( func ) { var tuples = [ // action, add listener, listener list, final state [ 'resolve', 'done', Callbacks( true ), 'resolved' ], [ 'reject', 'fail', Callbacks( true ), 'rejected' ], [ 'notify', 'progress', Callbacks() ] ], state = 'pending', promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return Deferred(function( newDefer ) { $.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = $.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for // forwarding actions to newDefer deferred[ tuple[ 1 ] ](function() { var returned; returned = fn && fn.apply( this, arguments ); if ( returned && $.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + 'With' ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? $.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods $.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + 'With' ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[ 0 ] + 'With' ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; } api = { /** * 创建一个[Deferred](http://api.jquery.com/category/deferred-object/)对象。 * 详细的Deferred用法说明,请参照jQuery的API文档。 * * Deferred对象在钩子回掉函数中经常要用到,用来处理需要等待的异步操作。 * * @for Base * @method Deferred * @grammar Base.Deferred() => Deferred * @example * // 在文件开始发送前做些异步操作。 * // WebUploader会等待此异步操作完成后,开始发送文件。 * Uploader.register({ * 'before-send-file': 'doSomthingAsync' * }, { * * doSomthingAsync: function() { * var deferred = Base.Deferred(); * * // 模拟一次异步操作。 * setTimeout(deferred.resolve, 2000); * * return deferred.promise(); * } * }); */ Deferred: Deferred, /** * 判断传入的参数是否为一个promise对象。 * @method isPromise * @grammar Base.isPromise( anything ) => Boolean * @param {*} anything 检测对象。 * @return {Boolean} * @for Base * @example * console.log( Base.isPromise() ); // => false * console.log( Base.isPromise({ key: '123' }) ); // => false * console.log( Base.isPromise( Base.Deferred().promise() ) ); // => true * * // Deferred也是一个Promise * console.log( Base.isPromise( Base.Deferred() ) ); // => true */ isPromise: function( anything ) { return anything && typeof anything.then === 'function'; }, /** * 返回一个promise,此promise在所有传入的promise都完成了后完成。 * 详细请查看[这里](http://api.jquery.com/jQuery.when/)。 * * @method when * @for Base * @grammar Base.when( promise1[, promise2[, promise3...]] ) => Promise */ when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, slice = [].slice, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || (subordinate && $.isFunction( subordinate.promise )) ? length : 0, // the master Deferred. If resolveValues consist of // only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && $.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }; return api; }); define('promise',[ 'promise-builtin' ], function( $ ) { return $; }); /** * @fileOverview 基础类方法。 */ /** * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。 * * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id. * 默认module id为该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如: * * * module `base`:WebUploader.Base * * module `file`: WebUploader.File * * module `lib/dnd`: WebUploader.Lib.Dnd * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd * * * 以下文档中对类的使用可能省略掉了`WebUploader`前缀。 * @module WebUploader * @title WebUploader API文档 */ define('base',[ 'dollar', 'promise' ], function( $, promise ) { var noop = function() {}, call = Function.call; // http://jsperf.com/uncurrythis // 反科里化 function uncurryThis( fn ) { return function() { return call.apply( fn, arguments ); }; } function bindFn( fn, context ) { return function() { return fn.apply( context, arguments ); }; } function createObject( proto ) { var f; if ( Object.create ) { return Object.create( proto ); } else { f = function() {}; f.prototype = proto; return new f(); } } /** * 基础类,提供一些简单常用的方法。 * @class Base */ return { /** * @property {String} version 当前版本号。 */ version: '0.1.5', /** * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。 */ $: $, Deferred: promise.Deferred, isPromise: promise.isPromise, when: promise.when, /** * @description 简单的浏览器检查结果。 * * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。 * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。 * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+** * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。 * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。 * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。 * * @property {Object} [browser] */ browser: (function( ua ) { var ret = {}, webkit = ua.match( /WebKit\/([\d.]+)/ ), chrome = ua.match( /Chrome\/([\d.]+)/ ) || ua.match( /CriOS\/([\d.]+)/ ), ie = ua.match( /MSIE\s([\d\.]+)/ ) || ua.match( /(?:trident)(?:.*rv:([\w.]+))?/i ), firefox = ua.match( /Firefox\/([\d.]+)/ ), safari = ua.match( /Safari\/([\d.]+)/ ), opera = ua.match( /OPR\/([\d.]+)/ ); webkit && (ret.webkit = parseFloat( webkit[ 1 ] )); chrome && (ret.chrome = parseFloat( chrome[ 1 ] )); ie && (ret.ie = parseFloat( ie[ 1 ] )); firefox && (ret.firefox = parseFloat( firefox[ 1 ] )); safari && (ret.safari = parseFloat( safari[ 1 ] )); opera && (ret.opera = parseFloat( opera[ 1 ] )); return ret; })( navigator.userAgent ), /** * @description 操作系统检查结果。 * * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。 * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。 * @property {Object} [os] */ os: (function( ua ) { var ret = {}, // osx = !!ua.match( /\(Macintosh\; Intel / ), android = ua.match( /(?:Android);?[\s\/]+([\d.]+)?/ ), ios = ua.match( /(?:iPad|iPod|iPhone).*OS\s([\d_]+)/ ); // osx && (ret.osx = true); android && (ret.android = parseFloat( android[ 1 ] )); ios && (ret.ios = parseFloat( ios[ 1 ].replace( /_/g, '.' ) )); return ret; })( navigator.userAgent ), /** * 实现类与类之间的继承。 * @method inherits * @grammar Base.inherits( super ) => child * @grammar Base.inherits( super, protos ) => child * @grammar Base.inherits( super, protos, statics ) => child * @param {Class} super 父类 * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。 * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。 * @param {Object} [statics] 静态属性或方法。 * @return {Class} 返回子类。 * @example * function Person() { * console.log( 'Super' ); * } * Person.prototype.hello = function() { * console.log( 'hello' ); * }; * * var Manager = Base.inherits( Person, { * world: function() { * console.log( 'World' ); * } * }); * * // 因为没有指定构造器,父类的构造器将会执行。 * var instance = new Manager(); // => Super * * // 继承子父类的方法 * instance.hello(); // => hello * instance.world(); // => World * * // 子类的__super__属性指向父类 * console.log( Manager.__super__ === Person ); // => true */ inherits: function( Super, protos, staticProtos ) { var child; if ( typeof protos === 'function' ) { child = protos; protos = null; } else if ( protos && protos.hasOwnProperty('constructor') ) { child = protos.constructor; } else { child = function() { return Super.apply( this, arguments ); }; } // 复制静态方法 $.extend( true, child, Super, staticProtos || {} ); /* jshint camelcase: false */ // 让子类的__super__属性指向父类。 child.__super__ = Super.prototype; // 构建原型,添加原型方法或属性。 // 暂时用Object.create实现。 child.prototype = createObject( Super.prototype ); protos && $.extend( true, child.prototype, protos ); return child; }, /** * 一个不做任何事情的方法。可以用来赋值给默认的callback. * @method noop */ noop: noop, /** * 返回一个新的方法,此方法将已指定的`context`来执行。 * @grammar Base.bindFn( fn, context ) => Function * @method bindFn * @example * var doSomething = function() { * console.log( this.name ); * }, * obj = { * name: 'Object Name' * }, * aliasFn = Base.bind( doSomething, obj ); * * aliasFn(); // => Object Name * */ bindFn: bindFn, /** * 引用Console.log如果存在的话,否则引用一个[空函数noop](#WebUploader:Base.noop)。 * @grammar Base.log( args... ) => undefined * @method log */ log: (function() { if ( window.console ) { return bindFn( console.log, console ); } return noop; })(), nextTick: (function() { return function( cb ) { setTimeout( cb, 1 ); }; // @bug 当浏览器不在当前窗口时就停了。 // var next = window.requestAnimationFrame || // window.webkitRequestAnimationFrame || // window.mozRequestAnimationFrame || // function( cb ) { // window.setTimeout( cb, 1000 / 60 ); // }; // // fix: Uncaught TypeError: Illegal invocation // return bindFn( next, window ); })(), /** * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。 * 将用来将非数组对象转化成数组对象。 * @grammar Base.slice( target, start[, end] ) => Array * @method slice * @example * function doSomthing() { * var args = Base.slice( arguments, 1 ); * console.log( args ); * } * * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"] */ slice: uncurryThis( [].slice ), /** * 生成唯一的ID * @method guid * @grammar Base.guid() => String * @grammar Base.guid( prefx ) => String */ guid: (function() { var counter = 0; return function( prefix ) { var guid = (+new Date()).toString( 32 ), i = 0; for ( ; i < 5; i++ ) { guid += Math.floor( Math.random() * 65535 ).toString( 32 ); } return (prefix || 'wu_') + guid + (counter++).toString( 32 ); }; })(), /** * 格式化文件大小, 输出成带单位的字符串 * @method formatSize * @grammar Base.formatSize( size ) => String * @grammar Base.formatSize( size, pointLength ) => String * @grammar Base.formatSize( size, pointLength, units ) => String * @param {Number} size 文件大小 * @param {Number} [pointLength=2] 精确到的小数点数。 * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K. * @example * console.log( Base.formatSize( 100 ) ); // => 100B * console.log( Base.formatSize( 1024 ) ); // => 1.00K * console.log( Base.formatSize( 1024, 0 ) ); // => 1K * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB */ formatSize: function( size, pointLength, units ) { var unit; units = units || [ 'B', 'K', 'M', 'G', 'TB' ]; while ( (unit = units.shift()) && size > 1024 ) { size = size / 1024; } return (unit === 'B' ? size : size.toFixed( pointLength || 2 )) + unit; } }; }); /** * 事件处理类,可以独立使用,也可以扩展给对象使用。 * @fileOverview Mediator */ define('mediator',[ 'base' ], function( Base ) { var $ = Base.$, slice = [].slice, separator = /\s+/, protos; // 根据条件过滤出事件handlers. function findHandlers( arr, name, callback, context ) { return $.grep( arr, function( handler ) { return handler && (!name || handler.e === name) && (!callback || handler.cb === callback || handler.cb._cb === callback) && (!context || handler.ctx === context); }); } function eachEvent( events, callback, iterator ) { // 不支持对象,只支持多个event用空格隔开 $.each( (events || '').split( separator ), function( _, key ) { iterator( key, callback ); }); } function triggerHanders( events, args ) { var stoped = false, i = -1, len = events.length, handler; while ( ++i < len ) { handler = events[ i ]; if ( handler.cb.apply( handler.ctx2, args ) === false ) { stoped = true; break; } } return !stoped; } protos = { /** * 绑定事件。 * * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如 * ```javascript * var obj = {}; * * // 使得obj有事件行为 * Mediator.installTo( obj ); * * obj.on( 'testa', function( arg1, arg2 ) { * console.log( arg1, arg2 ); // => 'arg1', 'arg2' * }); * * obj.trigger( 'testa', 'arg1', 'arg2' ); * ``` * * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。 * 切会影响到`trigger`方法的返回值,为`false`。 * * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处, * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。 * ```javascript * obj.on( 'all', function( type, arg1, arg2 ) { * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2' * }); * ``` * * @method on * @grammar on( name, callback[, context] ) => self * @param {String} name 事件名,支持多个事件用空格隔开 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable * @class Mediator */ on: function( name, callback, context ) { var me = this, set; if ( !callback ) { return this; } set = this._events || (this._events = []); eachEvent( name, callback, function( name, callback ) { var handler = { e: name }; handler.cb = callback; handler.ctx = context; handler.ctx2 = context || me; handler.id = set.length; set.push( handler ); }); return this; }, /** * 绑定事件,且当handler执行完后,自动解除绑定。 * @method once * @grammar once( name, callback[, context] ) => self * @param {String} name 事件名 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ once: function( name, callback, context ) { var me = this; if ( !callback ) { return me; } eachEvent( name, callback, function( name, callback ) { var once = function() { me.off( name, once ); return callback.apply( context || me, arguments ); }; once._cb = callback; me.on( name, once, context ); }); return me; }, /** * 解除事件绑定 * @method off * @grammar off( [name[, callback[, context] ] ] ) => self * @param {String} [name] 事件名 * @param {Function} [callback] 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ off: function( name, cb, ctx ) { var events = this._events; if ( !events ) { return this; } if ( !name && !cb && !ctx ) { this._events = []; return this; } eachEvent( name, cb, function( name, cb ) { $.each( findHandlers( events, name, cb, ctx ), function() { delete events[ this.id ]; }); }); return this; }, /** * 触发事件 * @method trigger * @grammar trigger( name[, args...] ) => self * @param {String} type 事件名 * @param {*} [...] 任意参数 * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true */ trigger: function( type ) { var args, events, allEvents; if ( !this._events || !type ) { return this; } args = slice.call( arguments, 1 ); events = findHandlers( this._events, type ); allEvents = findHandlers( this._events, 'all' ); return triggerHanders( events, args ) && triggerHanders( allEvents, arguments ); } }; /** * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。 * 主要目的是负责模块与模块之间的合作,降低耦合度。 * * @class Mediator */ return $.extend({ /** * 可以通过这个接口,使任何对象具备事件功能。 * @method installTo * @param {Object} obj 需要具备事件行为的对象。 * @return {Object} 返回obj. */ installTo: function( obj ) { return $.extend( obj, protos ); } }, protos ); }); /** * @fileOverview Uploader上传类 */ define('uploader',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$; /** * 上传入口类。 * @class Uploader * @constructor * @grammar new Uploader( opts ) => Uploader * @example * var uploader = WebUploader.Uploader({ * swf: 'path_of_swf/Uploader.swf', * * // 开起分片上传。 * chunked: true * }); */ function Uploader( opts ) { this.options = $.extend( true, {}, Uploader.options, opts ); this._init( this.options ); } // default Options // widgets中有相应扩展 Uploader.options = {}; Mediator.installTo( Uploader.prototype ); // 批量添加纯命令式方法。 $.each({ upload: 'start-upload', stop: 'stop-upload', getFile: 'get-file', getFiles: 'get-files', addFile: 'add-file', addFiles: 'add-file', sort: 'sort-files', removeFile: 'remove-file', cancelFile: 'cancel-file', skipFile: 'skip-file', retry: 'retry', isInProgress: 'is-in-progress', makeThumb: 'make-thumb', md5File: 'md5-file', getDimension: 'get-dimension', addButton: 'add-btn', predictRuntimeType: 'predict-runtime-type', refresh: 'refresh', disable: 'disable', enable: 'enable', reset: 'reset' }, function( fn, command ) { Uploader.prototype[ fn ] = function() { return this.request( command, arguments ); }; }); $.extend( Uploader.prototype, { state: 'pending', _init: function( opts ) { var me = this; me.request( 'init', opts, function() { me.state = 'ready'; me.trigger('ready'); }); }, /** * 获取或者设置Uploader配置项。 * @method option * @grammar option( key ) => * * @grammar option( key, val ) => self * @example * * // 初始状态图片上传前不会压缩 * var uploader = new WebUploader.Uploader({ * compress: null; * }); * * // 修改后图片上传前,尝试将图片压缩到1600 * 1600 * uploader.option( 'compress', { * width: 1600, * height: 1600 * }); */ option: function( key, val ) { var opts = this.options; // setter if ( arguments.length > 1 ) { if ( $.isPlainObject( val ) && $.isPlainObject( opts[ key ] ) ) { $.extend( opts[ key ], val ); } else { opts[ key ] = val; } } else { // getter return key ? opts[ key ] : opts; } }, /** * 获取文件统计信息。返回一个包含一下信息的对象。 * * `successNum` 上传成功的文件数 * * `progressNum` 上传中的文件数 * * `cancelNum` 被删除的文件数 * * `invalidNum` 无效的文件数 * * `uploadFailNum` 上传失败的文件数 * * `queueNum` 还在队列中的文件数 * * `interruptNum` 被暂停的文件数 * @method getStats * @grammar getStats() => Object */ getStats: function() { // return this._mgr.getStats.apply( this._mgr, arguments ); var stats = this.request('get-stats'); return stats ? { successNum: stats.numOfSuccess, progressNum: stats.numOfProgress, // who care? // queueFailNum: 0, cancelNum: stats.numOfCancel, invalidNum: stats.numOfInvalid, uploadFailNum: stats.numOfUploadFailed, queueNum: stats.numOfQueue, interruptNum: stats.numofInterrupt } : {}; }, // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器 trigger: function( type/*, args...*/ ) { var args = [].slice.call( arguments, 1 ), opts = this.options, name = 'on' + type.substring( 0, 1 ).toUpperCase() + type.substring( 1 ); if ( // 调用通过on方法注册的handler. Mediator.trigger.apply( this, arguments ) === false || // 调用opts.onEvent $.isFunction( opts[ name ] ) && opts[ name ].apply( this, args ) === false || // 调用this.onEvent $.isFunction( this[ name ] ) && this[ name ].apply( this, args ) === false || // 广播所有uploader的事件。 Mediator.trigger.apply( Mediator, [ this, type ].concat( args ) ) === false ) { return false; } return true; }, /** * 销毁 webuploader 实例 * @method destroy * @grammar destroy() => undefined */ destroy: function() { this.request( 'destroy', arguments ); this.off(); }, // widgets/widget.js将补充此方法的详细文档。 request: Base.noop }); /** * 创建Uploader实例,等同于new Uploader( opts ); * @method create * @class Base * @static * @grammar Base.create( opts ) => Uploader */ Base.create = Uploader.create = function( opts ) { return new Uploader( opts ); }; // 暴露Uploader,可以通过它来扩展业务逻辑。 Base.Uploader = Uploader; return Uploader; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/runtime',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$, factories = {}, // 获取对象的第一个key getFirstKey = function( obj ) { for ( var key in obj ) { if ( obj.hasOwnProperty( key ) ) { return key; } } return null; }; // 接口类。 function Runtime( options ) { this.options = $.extend({ container: document.body }, options ); this.uid = Base.guid('rt_'); } $.extend( Runtime.prototype, { getContainer: function() { var opts = this.options, parent, container; if ( this._container ) { return this._container; } parent = $( opts.container || document.body ); container = $( document.createElement('div') ); container.attr( 'id', 'rt_' + this.uid ); container.css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); parent.append( container ); parent.addClass('webuploader-container'); this._container = container; this._parent = parent; return container; }, init: Base.noop, exec: Base.noop, destroy: function() { this._container && this._container.remove(); this._parent && this._parent.removeClass('webuploader-container'); this.off(); } }); Runtime.orders = 'html5,flash'; /** * 添加Runtime实现。 * @param {String} type 类型 * @param {Runtime} factory 具体Runtime实现。 */ Runtime.addRuntime = function( type, factory ) { factories[ type ] = factory; }; Runtime.hasRuntime = function( type ) { return !!(type ? factories[ type ] : getFirstKey( factories )); }; Runtime.create = function( opts, orders ) { var type, runtime; orders = orders || Runtime.orders; $.each( orders.split( /\s*,\s*/g ), function() { if ( factories[ this ] ) { type = this; return false; } }); type = type || getFirstKey( factories ); if ( !type ) { throw new Error('Runtime Error'); } runtime = new factories[ type ]( opts ); return runtime; }; Mediator.installTo( Runtime.prototype ); return Runtime; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/client',[ 'base', 'mediator', 'runtime/runtime' ], function( Base, Mediator, Runtime ) { var cache; cache = (function() { var obj = {}; return { add: function( runtime ) { obj[ runtime.uid ] = runtime; }, get: function( ruid, standalone ) { var i; if ( ruid ) { return obj[ ruid ]; } for ( i in obj ) { // 有些类型不能重用,比如filepicker. if ( standalone && obj[ i ].__standalone ) { continue; } return obj[ i ]; } return null; }, remove: function( runtime ) { delete obj[ runtime.uid ]; } }; })(); function RuntimeClient( component, standalone ) { var deferred = Base.Deferred(), runtime; this.uid = Base.guid('client_'); // 允许runtime没有初始化之前,注册一些方法在初始化后执行。 this.runtimeReady = function( cb ) { return deferred.done( cb ); }; this.connectRuntime = function( opts, cb ) { // already connected. if ( runtime ) { throw new Error('already connected!'); } deferred.done( cb ); if ( typeof opts === 'string' && cache.get( opts ) ) { runtime = cache.get( opts ); } // 像filePicker只能独立存在,不能公用。 runtime = runtime || cache.get( null, standalone ); // 需要创建 if ( !runtime ) { runtime = Runtime.create( opts, opts.runtimeOrder ); runtime.__promise = deferred.promise(); runtime.once( 'ready', deferred.resolve ); runtime.init(); cache.add( runtime ); runtime.__client = 1; } else { // 来自cache Base.$.extend( runtime.options, opts ); runtime.__promise.then( deferred.resolve ); runtime.__client++; } standalone && (runtime.__standalone = standalone); return runtime; }; this.getRuntime = function() { return runtime; }; this.disconnectRuntime = function() { if ( !runtime ) { return; } runtime.__client--; if ( runtime.__client <= 0 ) { cache.remove( runtime ); delete runtime.__promise; runtime.destroy(); } runtime = null; }; this.exec = function() { if ( !runtime ) { return; } var args = Base.slice( arguments ); component && args.unshift( component ); return runtime.exec.apply( this, args ); }; this.getRuid = function() { return runtime && runtime.uid; }; this.destroy = (function( destroy ) { return function() { destroy && destroy.apply( this, arguments ); this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }; })( this.destroy ); } Mediator.installTo( RuntimeClient.prototype ); return RuntimeClient; }); /** * @fileOverview Blob */ define('lib/blob',[ 'base', 'runtime/client' ], function( Base, RuntimeClient ) { function Blob( ruid, source ) { var me = this; me.source = source; me.ruid = ruid; this.size = source.size || 0; // 如果没有指定 mimetype, 但是知道文件后缀。 if ( !source.type && this.ext && ~'jpg,jpeg,png,gif,bmp'.indexOf( this.ext ) ) { this.type = 'image/' + (this.ext === 'jpg' ? 'jpeg' : this.ext); } else { this.type = source.type || 'application/octet-stream'; } RuntimeClient.call( me, 'Blob' ); this.uid = source.uid || this.uid; if ( ruid ) { me.connectRuntime( ruid ); } } Base.inherits( RuntimeClient, { constructor: Blob, slice: function( start, end ) { return this.exec( 'slice', start, end ); }, getSource: function() { return this.source; } }); return Blob; }); /** * 为了统一化Flash的File和HTML5的File而存在。 * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。 * @fileOverview File */ define('lib/file',[ 'base', 'lib/blob' ], function( Base, Blob ) { var uid = 1, rExt = /\.([^.]+)$/; function File( ruid, file ) { var ext; this.name = file.name || ('untitled' + uid++); ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : ''; // 如果有 mimetype, 但是文件名里面没有找出后缀规律 if ( !ext && file.type ) { ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( file.type ) ? RegExp.$1.toLowerCase() : ''; this.name += '.' + ext; } this.ext = ext; this.lastModifiedDate = file.lastModifiedDate || (new Date()).toLocaleString(); Blob.apply( this, arguments ); } return Base.inherits( Blob, File ); }); /** * @fileOverview 错误信息 */ define('lib/filepicker',[ 'base', 'runtime/client', 'lib/file' ], function( Base, RuntimeClent, File ) { var $ = Base.$; function FilePicker( opts ) { opts = this.options = $.extend({}, FilePicker.options, opts ); opts.container = $( opts.id ); if ( !opts.container.length ) { throw new Error('按钮指定错误'); } opts.innerHTML = opts.innerHTML || opts.label || opts.container.html() || ''; opts.button = $( opts.button || document.createElement('div') ); opts.button.html( opts.innerHTML ); opts.container.html( opts.button ); RuntimeClent.call( this, 'FilePicker', true ); } FilePicker.options = { button: null, container: null, label: null, innerHTML: null, multiple: true, accept: null, name: 'file' }; Base.inherits( RuntimeClent, { constructor: FilePicker, init: function() { var me = this, opts = me.options, button = opts.button; button.addClass('webuploader-pick'); me.on( 'all', function( type ) { var files; switch ( type ) { case 'mouseenter': button.addClass('webuploader-pick-hover'); break; case 'mouseleave': button.removeClass('webuploader-pick-hover'); break; case 'change': files = me.exec('getFiles'); me.trigger( 'select', $.map( files, function( file ) { file = new File( me.getRuid(), file ); // 记录来源。 file._refer = opts.container; return file; }), opts.container ); break; } }); me.connectRuntime( opts, function() { me.refresh(); me.exec( 'init', opts ); me.trigger('ready'); }); this._resizeHandler = Base.bindFn( this.refresh, this ); $( window ).on( 'resize', this._resizeHandler ); }, refresh: function() { var shimContainer = this.getRuntime().getContainer(), button = this.options.button, width = button.outerWidth ? button.outerWidth() : button.width(), height = button.outerHeight ? button.outerHeight() : button.height(), pos = button.offset(); width && height && shimContainer.css({ bottom: 'auto', right: 'auto', width: width + 'px', height: height + 'px' }).offset( pos ); }, enable: function() { var btn = this.options.button; btn.removeClass('webuploader-pick-disable'); this.refresh(); }, disable: function() { var btn = this.options.button; this.getRuntime().getContainer().css({ top: '-99999px' }); btn.addClass('webuploader-pick-disable'); }, destroy: function() { var btn = this.options.button; $( window ).off( 'resize', this._resizeHandler ); btn.removeClass('webuploader-pick-disable webuploader-pick-hover ' + 'webuploader-pick'); } }); return FilePicker; }); /** * @fileOverview 组件基类。 */ define('widgets/widget',[ 'base', 'uploader' ], function( Base, Uploader ) { var $ = Base.$, _init = Uploader.prototype._init, _destroy = Uploader.prototype.destroy, IGNORE = {}, widgetClass = []; function isArrayLike( obj ) { if ( !obj ) { return false; } var length = obj.length, type = $.type( obj ); if ( obj.nodeType === 1 && length ) { return true; } return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj); } function Widget( uploader ) { this.owner = uploader; this.options = uploader.options; } $.extend( Widget.prototype, { init: Base.noop, // 类Backbone的事件监听声明,监听uploader实例上的事件 // widget直接无法监听事件,事件只能通过uploader来传递 invoke: function( apiName, args ) { /* { 'make-thumb': 'makeThumb' } */ var map = this.responseMap; // 如果无API响应声明则忽略 if ( !map || !(apiName in map) || !(map[ apiName ] in this) || !$.isFunction( this[ map[ apiName ] ] ) ) { return IGNORE; } return this[ map[ apiName ] ].apply( this, args ); }, /** * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。 * @method request * @grammar request( command, args ) => * | Promise * @grammar request( command, args, callback ) => Promise * @for Uploader */ request: function() { return this.owner.request.apply( this.owner, arguments ); } }); // 扩展Uploader. $.extend( Uploader.prototype, { /** * @property {String | Array} [disableWidgets=undefined] * @namespace options * @for Uploader * @description 默认所有 Uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。 */ // 覆写_init用来初始化widgets _init: function() { var me = this, widgets = me._widgets = [], deactives = me.options.disableWidgets || ''; $.each( widgetClass, function( _, klass ) { (!deactives || !~deactives.indexOf( klass._name )) && widgets.push( new klass( me ) ); }); return _init.apply( me, arguments ); }, request: function( apiName, args, callback ) { var i = 0, widgets = this._widgets, len = widgets && widgets.length, rlts = [], dfds = [], widget, rlt, promise, key; args = isArrayLike( args ) ? args : [ args ]; for ( ; i < len; i++ ) { widget = widgets[ i ]; rlt = widget.invoke( apiName, args ); if ( rlt !== IGNORE ) { // Deferred对象 if ( Base.isPromise( rlt ) ) { dfds.push( rlt ); } else { rlts.push( rlt ); } } } // 如果有callback,则用异步方式。 if ( callback || dfds.length ) { promise = Base.when.apply( Base, dfds ); key = promise.pipe ? 'pipe' : 'then'; // 很重要不能删除。删除了会死循环。 // 保证执行顺序。让callback总是在下一个 tick 中执行。 return promise[ key ](function() { var deferred = Base.Deferred(), args = arguments; if ( args.length === 1 ) { args = args[ 0 ]; } setTimeout(function() { deferred.resolve( args ); }, 1 ); return deferred.promise(); })[ callback ? key : 'done' ]( callback || Base.noop ); } else { return rlts[ 0 ]; } }, destroy: function() { _destroy.apply( this, arguments ); this._widgets = null; } }); /** * 添加组件 * @grammar Uploader.register(proto); * @grammar Uploader.register(map, proto); * @param {object} responseMap API 名称与函数实现的映射 * @param {object} proto 组件原型,构造函数通过 constructor 属性定义 * @method Uploader.register * @for Uploader * @example * Uploader.register({ * 'make-thumb': 'makeThumb' * }, { * init: function( options ) {}, * makeThumb: function() {} * }); * * Uploader.register({ * 'make-thumb': function() { * * } * }); */ Uploader.register = Widget.register = function( responseMap, widgetProto ) { var map = { init: 'init', destroy: 'destroy', name: 'anonymous' }, klass; if ( arguments.length === 1 ) { widgetProto = responseMap; // 自动生成 map 表。 $.each(widgetProto, function(key) { if ( key[0] === '_' || key === 'name' ) { key === 'name' && (map.name = widgetProto.name); return; } map[key.replace(/[A-Z]/g, '-$&').toLowerCase()] = key; }); } else { map = $.extend( map, responseMap ); } widgetProto.responseMap = map; klass = Base.inherits( Widget, widgetProto ); klass._name = map.name; widgetClass.push( klass ); return klass; }; /** * 删除插件,只有在注册时指定了名字的才能被删除。 * @grammar Uploader.unRegister(name); * @param {string} name 组件名字 * @method Uploader.unRegister * @for Uploader * @example * * Uploader.register({ * name: 'custom', * * 'make-thumb': function() { * * } * }); * * Uploader.unRegister('custom'); */ Uploader.unRegister = Widget.unRegister = function( name ) { if ( !name || name === 'anonymous' ) { return; } // 删除指定的插件。 for ( var i = widgetClass.length; i--; ) { if ( widgetClass[i]._name === name ) { widgetClass.splice(i, 1) } } }; return Widget; }); /** * @fileOverview 文件选择相关 */ define('widgets/filepicker',[ 'base', 'uploader', 'lib/filepicker', 'widgets/widget' ], function( Base, Uploader, FilePicker ) { var $ = Base.$; $.extend( Uploader.options, { /** * @property {Selector | Object} [pick=undefined] * @namespace options * @for Uploader * @description 指定选择文件的按钮容器,不指定则不创建按钮。 * * * `id` {Seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。 * * `label` {String} 请采用 `innerHTML` 代替 * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。 * * `multiple` {Boolean} 是否开起同时选择多个文件能力。 */ pick: null, /** * @property {Arroy} [accept=null] * @namespace options * @for Uploader * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。 * * * `title` {String} 文字描述 * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。 * * `mimeTypes` {String} 多个用逗号分割。 * * 如: * * ``` * { * title: 'Images', * extensions: 'gif,jpg,jpeg,bmp,png', * mimeTypes: 'image/*' * } * ``` */ accept: null/*{ title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }*/ }); return Uploader.register({ name: 'picker', init: function( opts ) { this.pickers = []; return opts.pick && this.addBtn( opts.pick ); }, refresh: function() { $.each( this.pickers, function() { this.refresh(); }); }, /** * @method addButton * @for Uploader * @grammar addButton( pick ) => Promise * @description * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。 * @example * uploader.addButton({ * id: '#btnContainer', * innerHTML: '选择文件' * }); */ addBtn: function( pick ) { var me = this, opts = me.options, accept = opts.accept, promises = []; if ( !pick ) { return; } $.isPlainObject( pick ) || (pick = { id: pick }); $( pick.id ).each(function() { var options, picker, deferred; deferred = Base.Deferred(); options = $.extend({}, pick, { accept: $.isPlainObject( accept ) ? [ accept ] : accept, swf: opts.swf, runtimeOrder: opts.runtimeOrder, id: this }); picker = new FilePicker( options ); picker.once( 'ready', deferred.resolve ); picker.on( 'select', function( files ) { me.owner.request( 'add-file', [ files ]); }); picker.init(); me.pickers.push( picker ); promises.push( deferred.promise() ); }); return Base.when.apply( Base, promises ); }, disable: function() { $.each( this.pickers, function() { this.disable(); }); }, enable: function() { $.each( this.pickers, function() { this.enable(); }); }, destroy: function() { $.each( this.pickers, function() { this.destroy(); }); this.pickers = null; } }); }); /** * @fileOverview Image */ define('lib/image',[ 'base', 'runtime/client', 'lib/blob' ], function( Base, RuntimeClient, Blob ) { var $ = Base.$; // 构造器。 function Image( opts ) { this.options = $.extend({}, Image.options, opts ); RuntimeClient.call( this, 'Image' ); this.on( 'load', function() { this._info = this.exec('info'); this._meta = this.exec('meta'); }); } // 默认选项。 Image.options = { // 默认的图片处理质量 quality: 90, // 是否裁剪 crop: false, // 是否保留头部信息 preserveHeaders: false, // 是否允许放大。 allowMagnify: false }; // 继承RuntimeClient. Base.inherits( RuntimeClient, { constructor: Image, info: function( val ) { // setter if ( val ) { this._info = val; return this; } // getter return this._info; }, meta: function( val ) { // setter if ( val ) { this._meta = val; return this; } // getter return this._meta; }, loadFromBlob: function( blob ) { var me = this, ruid = blob.getRuid(); this.connectRuntime( ruid, function() { me.exec( 'init', me.options ); me.exec( 'loadFromBlob', blob ); }); }, resize: function() { var args = Base.slice( arguments ); return this.exec.apply( this, [ 'resize' ].concat( args ) ); }, crop: function() { var args = Base.slice( arguments ); return this.exec.apply( this, [ 'crop' ].concat( args ) ); }, getAsDataUrl: function( type ) { return this.exec( 'getAsDataUrl', type ); }, getAsBlob: function( type ) { var blob = this.exec( 'getAsBlob', type ); return new Blob( this.getRuid(), blob ); } }); return Image; }); /** * @fileOverview 图片操作, 负责预览图片和上传前压缩图片 */ define('widgets/image',[ 'base', 'uploader', 'lib/image', 'widgets/widget' ], function( Base, Uploader, Image ) { var $ = Base.$, throttle; // 根据要处理的文件大小来节流,一次不能处理太多,会卡。 throttle = (function( max ) { var occupied = 0, waiting = [], tick = function() { var item; while ( waiting.length && occupied < max ) { item = waiting.shift(); occupied += item[ 0 ]; item[ 1 ](); } }; return function( emiter, size, cb ) { waiting.push([ size, cb ]); emiter.once( 'destroy', function() { occupied -= size; setTimeout( tick, 1 ); }); setTimeout( tick, 1 ); }; })( 5 * 1024 * 1024 ); $.extend( Uploader.options, { /** * @property {Object} [thumb] * @namespace options * @for Uploader * @description 配置生成缩略图的选项。 * * 默认为: * * ```javascript * { * width: 110, * height: 110, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 70, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: true, * * // 是否允许裁剪。 * crop: true, * * // 为空的话则保留原有图片格式。 * // 否则强制转换成指定的类型。 * type: 'image/jpeg' * } * ``` */ thumb: { width: 110, height: 110, quality: 70, allowMagnify: true, crop: true, preserveHeaders: false, // 为空的话则保留原有图片格式。 // 否则强制转换成指定的类型。 // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可 // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg type: 'image/jpeg' }, /** * @property {Object} [compress] * @namespace options * @for Uploader * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。 * * 默认为: * * ```javascript * { * width: 1600, * height: 1600, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 90, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: false, * * // 是否允许裁剪。 * crop: false, * * // 是否保留头部meta信息。 * preserveHeaders: true, * * // 如果发现压缩后文件大小比原来还大,则使用原来图片 * // 此属性可能会影响图片自动纠正功能 * noCompressIfLarger: false, * * // 单位字节,如果图片大小小于此值,不会采用压缩。 * compressSize: 0 * } * ``` */ compress: { width: 1600, height: 1600, quality: 90, allowMagnify: false, crop: false, preserveHeaders: true } }); return Uploader.register({ name: 'image', /** * 生成缩略图,此过程为异步,所以需要传入`callback`。 * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。 * * 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。 * * `callback`中可以接收到两个参数。 * * 第一个为error,如果生成缩略图有错误,此error将为真。 * * 第二个为ret, 缩略图的Data URL值。 * * **注意** * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。 * 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。 * * @method makeThumb * @grammar makeThumb( file, callback ) => undefined * @grammar makeThumb( file, callback, width, height ) => undefined * @for Uploader * @example * * uploader.on( 'fileQueued', function( file ) { * var $li = ...; * * uploader.makeThumb( file, function( error, ret ) { * if ( error ) { * $li.text('预览错误'); * } else { * $li.append('<img alt="" src="' + ret + '" />'); * } * }); * * }); */ makeThumb: function( file, cb, width, height ) { var opts, image; file = this.request( 'get-file', file ); // 只预览图片格式。 if ( !file.type.match( /^image/ ) ) { cb( true ); return; } opts = $.extend({}, this.options.thumb ); // 如果传入的是object. if ( $.isPlainObject( width ) ) { opts = $.extend( opts, width ); width = null; } width = width || opts.width; height = height || opts.height; image = new Image( opts ); image.once( 'load', function() { file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if ( width <= 1 && width > 0 ) { width = file._info.width * width; } // 同样的规则应用于 height if ( height <= 1 && height > 0 ) { height = file._info.height * height; } image.resize( width, height ); }); // 当 resize 完后 image.once( 'complete', function() { cb( false, image.getAsDataUrl( opts.type ) ); image.destroy(); }); image.once( 'error', function( reason ) { cb( reason || true ); image.destroy(); }); throttle( image, file.source.size, function() { file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); }); }, beforeSendFile: function( file ) { var opts = this.options.compress || this.options.resize, compressSize = opts && opts.compressSize || 0, noCompressIfLarger = opts && opts.noCompressIfLarger || false, image, deferred; file = this.request( 'get-file', file ); // 只压缩 jpeg 图片格式。 // gif 可能会丢失针 // bmp png 基本上尺寸都不大,且压缩比比较小。 if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) || file.size < compressSize || file._compressed ) { return; } opts = $.extend({}, opts ); deferred = Base.Deferred(); image = new Image( opts ); deferred.always(function() { image.destroy(); image = null; }); image.once( 'error', deferred.reject ); image.once( 'load', function() { var width = opts.width, height = opts.height; file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if ( width <= 1 && width > 0 ) { width = file._info.width * width; } // 同样的规则应用于 height if ( height <= 1 && height > 0 ) { height = file._info.height * height; } image.resize( width, height ); }); image.once( 'complete', function() { var blob, size; // 移动端 UC / qq 浏览器的无图模式下 // ctx.getImageData 处理大图的时候会报 Exception // INDEX_SIZE_ERR: DOM Exception 1 try { blob = image.getAsBlob( opts.type ); size = file.size; // 如果压缩后,比原来还大则不用压缩后的。 if ( !noCompressIfLarger || blob.size < size ) { // file.source.destroy && file.source.destroy(); file.source = blob; file.size = blob.size; file.trigger( 'resize', blob.size, size ); } // 标记,避免重复压缩。 file._compressed = true; deferred.resolve(); } catch ( e ) { // 出错了直接继续,让其上传原始图片 deferred.resolve(); } }); file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); return deferred.promise(); } }); }); /** * @fileOverview 文件属性封装 */ define('file',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$, idPrefix = 'WU_FILE_', idSuffix = 0, rExt = /\.([^.]+)$/, statusMap = {}; function gid() { return idPrefix + idSuffix++; } /** * 文件类 * @class File * @constructor 构造函数 * @grammar new File( source ) => File * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。 */ function WUFile( source ) { /** * 文件名,包括扩展名(后缀) * @property name * @type {string} */ this.name = source.name || 'Untitled'; /** * 文件体积(字节) * @property size * @type {uint} * @default 0 */ this.size = source.size || 0; /** * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny) * @property type * @type {string} * @default 'application/octet-stream' */ this.type = source.type || 'application/octet-stream'; /** * 文件最后修改日期 * @property lastModifiedDate * @type {int} * @default 当前时间戳 */ this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1); /** * 文件ID,每个对象具有唯一ID,与文件名无关 * @property id * @type {string} */ this.id = gid(); /** * 文件扩展名,通过文件名获取,例如test.png的扩展名为png * @property ext * @type {string} */ this.ext = rExt.exec( this.name ) ? RegExp.$1 : ''; /** * 状态文字说明。在不同的status语境下有不同的用途。 * @property statusText * @type {string} */ this.statusText = ''; // 存储文件状态,防止通过属性直接修改 statusMap[ this.id ] = WUFile.Status.INITED; this.source = source; this.loaded = 0; this.on( 'error', function( msg ) { this.setStatus( WUFile.Status.ERROR, msg ); }); } $.extend( WUFile.prototype, { /** * 设置状态,状态变化时会触发`change`事件。 * @method setStatus * @grammar setStatus( status[, statusText] ); * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status) * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。 */ setStatus: function( status, text ) { var prevStatus = statusMap[ this.id ]; typeof text !== 'undefined' && (this.statusText = text); if ( status !== prevStatus ) { statusMap[ this.id ] = status; /** * 文件状态变化 * @event statuschange */ this.trigger( 'statuschange', status, prevStatus ); } }, /** * 获取文件状态 * @return {File.Status} * @example 文件状态具体包括以下几种类型: { // 初始化 INITED: 0, // 已入队列 QUEUED: 1, // 正在上传 PROGRESS: 2, // 上传出错 ERROR: 3, // 上传成功 COMPLETE: 4, // 上传取消 CANCELLED: 5 } */ getStatus: function() { return statusMap[ this.id ]; }, /** * 获取文件原始信息。 * @return {*} */ getSource: function() { return this.source; }, destroy: function() { this.off(); delete statusMap[ this.id ]; } }); Mediator.installTo( WUFile.prototype ); /** * 文件状态值,具体包括以下几种类型: * * `inited` 初始状态 * * `queued` 已经进入队列, 等待上传 * * `progress` 上传中 * * `complete` 上传完成。 * * `error` 上传出错,可重试 * * `interrupt` 上传中断,可续传。 * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。 * * `cancelled` 文件被移除。 * @property {Object} Status * @namespace File * @class File * @static */ WUFile.Status = { INITED: 'inited', // 初始状态 QUEUED: 'queued', // 已经进入队列, 等待上传 PROGRESS: 'progress', // 上传中 ERROR: 'error', // 上传出错,可重试 COMPLETE: 'complete', // 上传完成。 CANCELLED: 'cancelled', // 上传取消。 INTERRUPT: 'interrupt', // 上传中断,可续传。 INVALID: 'invalid' // 文件不合格,不能重试上传。 }; return WUFile; }); /** * @fileOverview 文件队列 */ define('queue',[ 'base', 'mediator', 'file' ], function( Base, Mediator, WUFile ) { var $ = Base.$, STATUS = WUFile.Status; /** * 文件队列, 用来存储各个状态中的文件。 * @class Queue * @extends Mediator */ function Queue() { /** * 统计文件数。 * * `numOfQueue` 队列中的文件数。 * * `numOfSuccess` 上传成功的文件数 * * `numOfCancel` 被取消的文件数 * * `numOfProgress` 正在上传中的文件数 * * `numOfUploadFailed` 上传错误的文件数。 * * `numOfInvalid` 无效的文件数。 * * `numofDeleted` 被移除的文件数。 * @property {Object} stats */ this.stats = { numOfQueue: 0, numOfSuccess: 0, numOfCancel: 0, numOfProgress: 0, numOfUploadFailed: 0, numOfInvalid: 0, numofDeleted: 0, numofInterrupt: 0 }; // 上传队列,仅包括等待上传的文件 this._queue = []; // 存储所有文件 this._map = {}; } $.extend( Queue.prototype, { /** * 将新文件加入对队列尾部 * * @method append * @param {File} file 文件对象 */ append: function( file ) { this._queue.push( file ); this._fileAdded( file ); return this; }, /** * 将新文件加入对队列头部 * * @method prepend * @param {File} file 文件对象 */ prepend: function( file ) { this._queue.unshift( file ); this._fileAdded( file ); return this; }, /** * 获取文件对象 * * @method getFile * @param {String} fileId 文件ID * @return {File} */ getFile: function( fileId ) { if ( typeof fileId !== 'string' ) { return fileId; } return this._map[ fileId ]; }, /** * 从队列中取出一个指定状态的文件。 * @grammar fetch( status ) => File * @method fetch * @param {String} status [文件状态值](#WebUploader:File:File.Status) * @return {File} [File](#WebUploader:File) */ fetch: function( status ) { var len = this._queue.length, i, file; status = status || STATUS.QUEUED; for ( i = 0; i < len; i++ ) { file = this._queue[ i ]; if ( status === file.getStatus() ) { return file; } } return null; }, /** * 对队列进行排序,能够控制文件上传顺序。 * @grammar sort( fn ) => undefined * @method sort * @param {Function} fn 排序方法 */ sort: function( fn ) { if ( typeof fn === 'function' ) { this._queue.sort( fn ); } }, /** * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。 * @grammar getFiles( [status1[, status2 ...]] ) => Array * @method getFiles * @param {String} [status] [文件状态值](#WebUploader:File:File.Status) */ getFiles: function() { var sts = [].slice.call( arguments, 0 ), ret = [], i = 0, len = this._queue.length, file; for ( ; i < len; i++ ) { file = this._queue[ i ]; if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) { continue; } ret.push( file ); } return ret; }, /** * 在队列中删除文件。 * @grammar removeFile( file ) => Array * @method removeFile * @param {File} 文件对象。 */ removeFile: function( file ) { var me = this, existing = this._map[ file.id ]; if ( existing ) { delete this._map[ file.id ]; file.destroy(); this.stats.numofDeleted++; } }, _fileAdded: function( file ) { var me = this, existing = this._map[ file.id ]; if ( !existing ) { this._map[ file.id ] = file; file.on( 'statuschange', function( cur, pre ) { me._onFileStatusChange( cur, pre ); }); } }, _onFileStatusChange: function( curStatus, preStatus ) { var stats = this.stats; switch ( preStatus ) { case STATUS.PROGRESS: stats.numOfProgress--; break; case STATUS.QUEUED: stats.numOfQueue --; break; case STATUS.ERROR: stats.numOfUploadFailed--; break; case STATUS.INVALID: stats.numOfInvalid--; break; case STATUS.INTERRUPT: stats.numofInterrupt--; break; } switch ( curStatus ) { case STATUS.QUEUED: stats.numOfQueue++; break; case STATUS.PROGRESS: stats.numOfProgress++; break; case STATUS.ERROR: stats.numOfUploadFailed++; break; case STATUS.COMPLETE: stats.numOfSuccess++; break; case STATUS.CANCELLED: stats.numOfCancel++; break; case STATUS.INVALID: stats.numOfInvalid++; break; case STATUS.INTERRUPT: stats.numofInterrupt++; break; } } }); Mediator.installTo( Queue.prototype ); return Queue; }); /** * @fileOverview 队列 */ define('widgets/queue',[ 'base', 'uploader', 'queue', 'file', 'lib/file', 'runtime/client', 'widgets/widget' ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) { var $ = Base.$, rExt = /\.\w+$/, Status = WUFile.Status; return Uploader.register({ name: 'queue', init: function( opts ) { var me = this, deferred, len, i, item, arr, accept, runtime; if ( $.isPlainObject( opts.accept ) ) { opts.accept = [ opts.accept ]; } // accept中的中生成匹配正则。 if ( opts.accept ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { item = opts.accept[ i ].extensions; item && arr.push( item ); } if ( arr.length ) { accept = '\\.' + arr.join(',') .replace( /,/g, '$|\\.' ) .replace( /\*/g, '.*' ) + '$'; } me.accept = new RegExp( accept, 'i' ); } me.queue = new Queue(); me.stats = me.queue.stats; // 如果当前不是html5运行时,那就算了。 // 不执行后续操作 if ( this.request('predict-runtime-type') !== 'html5' ) { return; } // 创建一个 html5 运行时的 placeholder // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。 deferred = Base.Deferred(); this.placeholder = runtime = new RuntimeClient('Placeholder'); runtime.connectRuntime({ runtimeOrder: 'html5' }, function() { me._ruid = runtime.getRuid(); deferred.resolve(); }); return deferred.promise(); }, // 为了支持外部直接添加一个原生File对象。 _wrapFile: function( file ) { if ( !(file instanceof WUFile) ) { if ( !(file instanceof File) ) { if ( !this._ruid ) { throw new Error('Can\'t add external files.'); } file = new File( this._ruid, file ); } file = new WUFile( file ); } return file; }, // 判断文件是否可以被加入队列 acceptFile: function( file ) { var invalid = !file || !file.size || this.accept && // 如果名字中有后缀,才做后缀白名单处理。 rExt.exec( file.name ) && !this.accept.test( file.name ); return !invalid; }, /** * @event beforeFileQueued * @param {File} file File对象 * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。 * @for Uploader */ /** * @event fileQueued * @param {File} file File对象 * @description 当文件被加入队列以后触发。 * @for Uploader */ _addFile: function( file ) { var me = this; file = me._wrapFile( file ); // 不过类型判断允许不允许,先派送 `beforeFileQueued` if ( !me.owner.trigger( 'beforeFileQueued', file ) ) { return; } // 类型不匹配,则派送错误事件,并返回。 if ( !me.acceptFile( file ) ) { me.owner.trigger( 'error', 'Q_TYPE_DENIED', file ); return; } me.queue.append( file ); me.owner.trigger( 'fileQueued', file ); return file; }, getFile: function( fileId ) { return this.queue.getFile( fileId ); }, /** * @event filesQueued * @param {File} files 数组,内容为原始File(lib/File)对象。 * @description 当一批文件添加进队列以后触发。 * @for Uploader */ /** * @property {Boolean} [auto=false] * @namespace options * @for Uploader * @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。 * */ /** * @method addFiles * @grammar addFiles( file ) => undefined * @grammar addFiles( [file1, file2 ...] ) => undefined * @param {Array of File or File} [files] Files 对象 数组 * @description 添加文件到队列 * @for Uploader */ addFile: function( files ) { var me = this; if ( !files.length ) { files = [ files ]; } files = $.map( files, function( file ) { return me._addFile( file ); }); me.owner.trigger( 'filesQueued', files ); if ( me.options.auto ) { setTimeout(function() { me.request('start-upload'); }, 20 ); } }, getStats: function() { return this.stats; }, /** * @event fileDequeued * @param {File} file File对象 * @description 当文件被移除队列后触发。 * @for Uploader */ /** * @method removeFile * @grammar removeFile( file ) => undefined * @grammar removeFile( id ) => undefined * @grammar removeFile( file, true ) => undefined * @grammar removeFile( id, true ) => undefined * @param {File|id} file File对象或这File对象的id * @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.removeFile( file ); * }) */ removeFile: function( file, remove ) { var me = this; file = file.id ? file : me.queue.getFile( file ); this.request( 'cancel-file', file ); if ( remove ) { this.queue.removeFile( file ); } }, /** * @method getFiles * @grammar getFiles() => Array * @grammar getFiles( status1, status2, status... ) => Array * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。 * @for Uploader * @example * console.log( uploader.getFiles() ); // => all files * console.log( uploader.getFiles('error') ) // => all error files. */ getFiles: function() { return this.queue.getFiles.apply( this.queue, arguments ); }, fetchFile: function() { return this.queue.fetch.apply( this.queue, arguments ); }, /** * @method retry * @grammar retry() => undefined * @grammar retry( file ) => undefined * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。 * @for Uploader * @example * function retry() { * uploader.retry(); * } */ retry: function( file, noForceStart ) { var me = this, files, i, len; if ( file ) { file = file.id ? file : me.queue.getFile( file ); file.setStatus( Status.QUEUED ); noForceStart || me.request('start-upload'); return; } files = me.queue.getFiles( Status.ERROR ); i = 0; len = files.length; for ( ; i < len; i++ ) { file = files[ i ]; file.setStatus( Status.QUEUED ); } me.request('start-upload'); }, /** * @method sort * @grammar sort( fn ) => undefined * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。 * @for Uploader */ sortFiles: function() { return this.queue.sort.apply( this.queue, arguments ); }, /** * @event reset * @description 当 uploader 被重置的时候触发。 * @for Uploader */ /** * @method reset * @grammar reset() => undefined * @description 重置uploader。目前只重置了队列。 * @for Uploader * @example * uploader.reset(); */ reset: function() { this.owner.trigger('reset'); this.queue = new Queue(); this.stats = this.queue.stats; }, destroy: function() { this.reset(); this.placeholder && this.placeholder.destroy(); } }); }); /** * @fileOverview 添加获取Runtime相关信息的方法。 */ define('widgets/runtime',[ 'uploader', 'runtime/runtime', 'widgets/widget' ], function( Uploader, Runtime ) { Uploader.support = function() { return Runtime.hasRuntime.apply( Runtime, arguments ); }; /** * @property {Object} [runtimeOrder=html5,flash] * @namespace options * @for Uploader * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash. * * 可以将此值设置成 `flash`,来强制使用 flash 运行时。 */ return Uploader.register({ name: 'runtime', init: function() { if ( !this.predictRuntimeType() ) { throw Error('Runtime Error'); } }, /** * 预测Uploader将采用哪个`Runtime` * @grammar predictRuntimeType() => String * @method predictRuntimeType * @for Uploader */ predictRuntimeType: function() { var orders = this.options.runtimeOrder || Runtime.orders, type = this.type, i, len; if ( !type ) { orders = orders.split( /\s*,\s*/g ); for ( i = 0, len = orders.length; i < len; i++ ) { if ( Runtime.hasRuntime( orders[ i ] ) ) { this.type = type = orders[ i ]; break; } } } return type; } }); }); /** * @fileOverview Transport */ define('lib/transport',[ 'base', 'runtime/client', 'mediator' ], function( Base, RuntimeClient, Mediator ) { var $ = Base.$; function Transport( opts ) { var me = this; opts = me.options = $.extend( true, {}, Transport.options, opts || {} ); RuntimeClient.call( this, 'Transport' ); this._blob = null; this._formData = opts.formData || {}; this._headers = opts.headers || {}; this.on( 'progress', this._timeout ); this.on( 'load error', function() { me.trigger( 'progress', 1 ); clearTimeout( me._timer ); }); } Transport.options = { server: '', method: 'POST', // 跨域时,是否允许携带cookie, 只有html5 runtime才有效 withCredentials: false, fileVal: 'file', timeout: 2 * 60 * 1000, // 2分钟 formData: {}, headers: {}, sendAsBinary: false }; $.extend( Transport.prototype, { // 添加Blob, 只能添加一次,最后一次有效。 appendBlob: function( key, blob, filename ) { var me = this, opts = me.options; if ( me.getRuid() ) { me.disconnectRuntime(); } // 连接到blob归属的同一个runtime. me.connectRuntime( blob.ruid, function() { me.exec('init'); }); me._blob = blob; opts.fileVal = key || opts.fileVal; opts.filename = filename || opts.filename; }, // 添加其他字段 append: function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._formData, key ); } else { this._formData[ key ] = value; } }, setRequestHeader: function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._headers, key ); } else { this._headers[ key ] = value; } }, send: function( method ) { this.exec( 'send', method ); this._timeout(); }, abort: function() { clearTimeout( this._timer ); return this.exec('abort'); }, destroy: function() { this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }, getResponse: function() { return this.exec('getResponse'); }, getResponseAsJson: function() { return this.exec('getResponseAsJson'); }, getStatus: function() { return this.exec('getStatus'); }, _timeout: function() { var me = this, duration = me.options.timeout; if ( !duration ) { return; } clearTimeout( me._timer ); me._timer = setTimeout(function() { me.abort(); me.trigger( 'error', 'timeout' ); }, duration ); } }); // 让Transport具备事件功能。 Mediator.installTo( Transport.prototype ); return Transport; }); /** * @fileOverview 负责文件上传相关。 */ define('widgets/upload',[ 'base', 'uploader', 'file', 'lib/transport', 'widgets/widget' ], function( Base, Uploader, WUFile, Transport ) { var $ = Base.$, isPromise = Base.isPromise, Status = WUFile.Status; // 添加默认配置项 $.extend( Uploader.options, { /** * @property {Boolean} [prepareNextFile=false] * @namespace options * @for Uploader * @description 是否允许在文件传输时提前把下一个文件准备好。 * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。 * 如果能提前在当前文件传输期处理,可以节省总体耗时。 */ prepareNextFile: false, /** * @property {Boolean} [chunked=false] * @namespace options * @for Uploader * @description 是否要分片处理大文件上传。 */ chunked: false, /** * @property {Boolean} [chunkSize=5242880] * @namespace options * @for Uploader * @description 如果要分片,分多大一片? 默认大小为5M. */ chunkSize: 5 * 1024 * 1024, /** * @property {Boolean} [chunkRetry=2] * @namespace options * @for Uploader * @description 如果某个分片由于网络问题出错,允许自动重传多少次? */ chunkRetry: 2, /** * @property {Boolean} [threads=3] * @namespace options * @for Uploader * @description 上传并发数。允许同时最大上传进程数。 */ threads: 3, /** * @property {Object} [formData={}] * @namespace options * @for Uploader * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。 */ formData: {} /** * @property {Object} [fileVal='file'] * @namespace options * @for Uploader * @description 设置文件上传域的name。 */ /** * @property {Object} [method='POST'] * @namespace options * @for Uploader * @description 文件上传方式,`POST`或者`GET`。 */ /** * @property {Object} [sendAsBinary=false] * @namespace options * @for Uploader * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容, * 其他参数在$_GET数组中。 */ }); // 负责将文件切片。 function CuteFile( file, chunkSize ) { var pending = [], blob = file.source, total = blob.size, chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1, start = 0, index = 0, len, api; api = { file: file, has: function() { return !!pending.length; }, shift: function() { return pending.shift(); }, unshift: function( block ) { pending.unshift( block ); } }; while ( index < chunks ) { len = Math.min( chunkSize, total - start ); pending.push({ file: file, start: start, end: chunkSize ? (start + len) : total, total: total, chunks: chunks, chunk: index++, cuted: api }); start += len; } file.blocks = pending.concat(); file.remaning = pending.length; return api; } Uploader.register({ name: 'upload', init: function() { var owner = this.owner, me = this; this.runing = false; this.progress = false; owner .on( 'startUpload', function() { me.progress = true; }) .on( 'uploadFinished', function() { me.progress = false; }); // 记录当前正在传的数据,跟threads相关 this.pool = []; // 缓存分好片的文件。 this.stack = []; // 缓存即将上传的文件。 this.pending = []; // 跟踪还有多少分片在上传中但是没有完成上传。 this.remaning = 0; this.__tick = Base.bindFn( this._tick, this ); owner.on( 'uploadComplete', function( file ) { // 把其他块取消了。 file.blocks && $.each( file.blocks, function( _, v ) { v.transport && (v.transport.abort(), v.transport.destroy()); delete v.transport; }); delete file.blocks; delete file.remaning; }); }, reset: function() { this.request( 'stop-upload', true ); this.runing = false; this.pool = []; this.stack = []; this.pending = []; this.remaning = 0; this._trigged = false; this._promise = null; }, /** * @event startUpload * @description 当开始上传流程时触发。 * @for Uploader */ /** * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。 * * 可以指定开始某一个文件。 * @grammar upload() => undefined * @grammar upload( file | fileId) => undefined * @method upload * @for Uploader */ startUpload: function(file) { var me = this; // 移出invalid的文件 $.each( me.request( 'get-files', Status.INVALID ), function() { me.request( 'remove-file', this ); }); // 如果指定了开始某个文件,则只开始指定文件。 if ( file ) { file = file.id ? file : me.request( 'get-file', file ); if (file.getStatus() === Status.INTERRUPT) { $.each( me.pool, function( _, v ) { // 之前暂停过。 if (v.file !== file) { return; } v.transport && v.transport.send(); }); file.setStatus( Status.QUEUED ); } else if (file.getStatus() === Status.PROGRESS) { return; } else { file.setStatus( Status.QUEUED ); } } else { $.each( me.request( 'get-files', [ Status.INITED ] ), function() { this.setStatus( Status.QUEUED ); }); } if ( me.runing ) { return; } me.runing = true; var files = []; // 如果有暂停的,则续传 $.each( me.pool, function( _, v ) { var file = v.file; if ( file.getStatus() === Status.INTERRUPT ) { files.push(file); me._trigged = false; v.transport && v.transport.send(); } }); var file; while ( (file = files.shift()) ) { file.setStatus( Status.PROGRESS ); } file || $.each( me.request( 'get-files', Status.INTERRUPT ), function() { this.setStatus( Status.PROGRESS ); }); me._trigged = false; Base.nextTick( me.__tick ); me.owner.trigger('startUpload'); }, /** * @event stopUpload * @description 当开始上传流程暂停时触发。 * @for Uploader */ /** * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。 * * 如果第一个参数是文件,则只暂停指定文件。 * @grammar stop() => undefined * @grammar stop( true ) => undefined * @grammar stop( file ) => undefined * @method stop * @for Uploader */ stopUpload: function( file, interrupt ) { var me = this; if (file === true) { interrupt = file; file = null; } if ( me.runing === false ) { return; } // 如果只是暂停某个文件。 if ( file ) { file = file.id ? file : me.request( 'get-file', file ); if ( file.getStatus() !== Status.PROGRESS && file.getStatus() !== Status.QUEUED ) { return; } file.setStatus( Status.INTERRUPT ); $.each( me.pool, function( _, v ) { // 只 abort 指定的文件。 if (v.file !== file) { return; } v.transport && v.transport.abort(); me._putback(v); me._popBlock(v); }); return Base.nextTick( me.__tick ); } me.runing = false; if (this._promise && this._promise.file) { this._promise.file.setStatus( Status.INTERRUPT ); } interrupt && $.each( me.pool, function( _, v ) { v.transport && v.transport.abort(); v.file.setStatus( Status.INTERRUPT ); }); me.owner.trigger('stopUpload'); }, /** * @method cancelFile * @grammar cancelFile( file ) => undefined * @grammar cancelFile( id ) => undefined * @param {File|id} file File对象或这File对象的id * @description 标记文件状态为已取消, 同时将中断文件传输。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.cancelFile( file ); * }) */ cancelFile: function( file ) { file = file.id ? file : this.request( 'get-file', file ); // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); file.setStatus( Status.CANCELLED ); this.owner.trigger( 'fileDequeued', file ); }, /** * 判断`Uplaode`r是否正在上传中。 * @grammar isInProgress() => Boolean * @method isInProgress * @for Uploader */ isInProgress: function() { return !!this.progress; }, _getStats: function() { return this.request('get-stats'); }, /** * 掉过一个文件上传,直接标记指定文件为已上传状态。 * @grammar skipFile( file ) => undefined * @method skipFile * @for Uploader */ skipFile: function( file, status ) { file = file.id ? file : this.request( 'get-file', file ); file.setStatus( status || Status.COMPLETE ); file.skipped = true; // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); this.owner.trigger( 'uploadSkip', file ); }, /** * @event uploadFinished * @description 当所有文件上传结束时触发。 * @for Uploader */ _tick: function() { var me = this, opts = me.options, fn, val; // 上一个promise还没有结束,则等待完成后再执行。 if ( me._promise ) { return me._promise.always( me.__tick ); } // 还有位置,且还有文件要处理的话。 if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) { me._trigged = false; fn = function( val ) { me._promise = null; // 有可能是reject过来的,所以要检测val的类型。 val && val.file && me._startSend( val ); Base.nextTick( me.__tick ); }; me._promise = isPromise( val ) ? val.always( fn ) : fn( val ); // 没有要上传的了,且没有正在传输的了。 } else if ( !me.remaning && !me._getStats().numOfQueue && !me._getStats().numofInterrupt ) { me.runing = false; me._trigged || Base.nextTick(function() { me.owner.trigger('uploadFinished'); }); me._trigged = true; } }, _putback: function(block) { var idx; block.cuted.unshift(block); idx = this.stack.indexOf(block.cuted); if (!~idx) { this.stack.unshift(block.cuted); } }, _getStack: function() { var i = 0, act; while ( (act = this.stack[ i++ ]) ) { if ( act.has() && act.file.getStatus() === Status.PROGRESS ) { return act; } else if (!act.has() || act.file.getStatus() !== Status.PROGRESS && act.file.getStatus() !== Status.INTERRUPT ) { // 把已经处理完了的,或者,状态为非 progress(上传中)、 // interupt(暂停中) 的移除。 this.stack.splice( --i, 1 ); } } return null; }, _nextBlock: function() { var me = this, opts = me.options, act, next, done, preparing; // 如果当前文件还有没有需要传输的,则直接返回剩下的。 if ( (act = this._getStack()) ) { // 是否提前准备下一个文件 if ( opts.prepareNextFile && !me.pending.length ) { me._prepareNextFile(); } return act.shift(); // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。 } else if ( me.runing ) { // 如果缓存中有,则直接在缓存中取,没有则去queue中取。 if ( !me.pending.length && me._getStats().numOfQueue ) { me._prepareNextFile(); } next = me.pending.shift(); done = function( file ) { if ( !file ) { return null; } act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 ); me.stack.push(act); return act.shift(); }; // 文件可能还在prepare中,也有可能已经完全准备好了。 if ( isPromise( next) ) { preparing = next.file; next = next[ next.pipe ? 'pipe' : 'then' ]( done ); next.file = preparing; return next; } return done( next ); } }, /** * @event uploadStart * @param {File} file File对象 * @description 某个文件开始上传前触发,一个文件只会触发一次。 * @for Uploader */ _prepareNextFile: function() { var me = this, file = me.request('fetch-file'), pending = me.pending, promise; if ( file ) { promise = me.request( 'before-send-file', file, function() { // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued. if ( file.getStatus() === Status.PROGRESS || file.getStatus() === Status.INTERRUPT ) { return file; } return me._finishFile( file ); }); me.owner.trigger( 'uploadStart', file ); file.setStatus( Status.PROGRESS ); promise.file = file; // 如果还在pending中,则替换成文件本身。 promise.done(function() { var idx = $.inArray( promise, pending ); ~idx && pending.splice( idx, 1, file ); }); // befeore-send-file的钩子就有错误发生。 promise.fail(function( reason ) { file.setStatus( Status.ERROR, reason ); me.owner.trigger( 'uploadError', file, reason ); me.owner.trigger( 'uploadComplete', file ); }); pending.push( promise ); } }, // 让出位置了,可以让其他分片开始上传 _popBlock: function( block ) { var idx = $.inArray( block, this.pool ); this.pool.splice( idx, 1 ); block.file.remaning--; this.remaning--; }, // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。 _startSend: function( block ) { var me = this, file = block.file, promise; // 有可能在 before-send-file 的 promise 期间改变了文件状态。 // 如:暂停,取消 // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。 if ( file.getStatus() !== Status.PROGRESS ) { // 如果是中断,则还需要放回去。 if (file.getStatus() === Status.INTERRUPT) { me._putback(block); } return; } me.pool.push( block ); me.remaning++; // 如果没有分片,则直接使用原始的。 // 不会丢失content-type信息。 block.blob = block.chunks === 1 ? file.source : file.source.slice( block.start, block.end ); // hook, 每个分片发送之前可能要做些异步的事情。 promise = me.request( 'before-send', block, function() { // 有可能文件已经上传出错了,所以不需要再传输了。 if ( file.getStatus() === Status.PROGRESS ) { me._doSend( block ); } else { me._popBlock( block ); Base.nextTick( me.__tick ); } }); // 如果为fail了,则跳过此分片。 promise.fail(function() { if ( file.remaning === 1 ) { me._finishFile( file ).always(function() { block.percentage = 1; me._popBlock( block ); me.owner.trigger( 'uploadComplete', file ); Base.nextTick( me.__tick ); }); } else { block.percentage = 1; me.updateFileProgress( file ); me._popBlock( block ); Base.nextTick( me.__tick ); } }); }, /** * @event uploadBeforeSend * @param {Object} object * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。 * @param {Object} headers 可以扩展此对象来控制上传头部。 * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。 * @for Uploader */ /** * @event uploadAccept * @param {Object} object * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。 * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。 * @for Uploader */ /** * @event uploadProgress * @param {File} file File对象 * @param {Number} percentage 上传进度 * @description 上传过程中触发,携带上传进度。 * @for Uploader */ /** * @event uploadError * @param {File} file File对象 * @param {String} reason 出错的code * @description 当文件上传出错时触发。 * @for Uploader */ /** * @event uploadSuccess * @param {File} file File对象 * @param {Object} response 服务端返回的数据 * @description 当文件上传成功时触发。 * @for Uploader */ /** * @event uploadComplete * @param {File} [file] File对象 * @description 不管成功或者失败,文件上传完成时触发。 * @for Uploader */ // 做上传操作。 _doSend: function( block ) { var me = this, owner = me.owner, opts = me.options, file = block.file, tr = new Transport( opts ), data = $.extend({}, opts.formData ), headers = $.extend({}, opts.headers ), requestAccept, ret; block.transport = tr; tr.on( 'destroy', function() { delete block.transport; me._popBlock( block ); Base.nextTick( me.__tick ); }); // 广播上传进度。以文件为单位。 tr.on( 'progress', function( percentage ) { block.percentage = percentage; me.updateFileProgress( file ); }); // 用来询问,是否返回的结果是有错误的。 requestAccept = function( reject ) { var fn; ret = tr.getResponseAsJson() || {}; ret._raw = tr.getResponse(); fn = function( value ) { reject = value; }; // 服务端响应了,不代表成功了,询问是否响应正确。 if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) { reject = reject || 'server'; } return reject; }; // 尝试重试,然后广播文件上传出错。 tr.on( 'error', function( type, flag ) { block.retried = block.retried || 0; // 自动重试 if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) && block.retried < opts.chunkRetry ) { block.retried++; tr.send(); } else { // http status 500 ~ 600 if ( !flag && type === 'server' ) { type = requestAccept( type ); } file.setStatus( Status.ERROR, type ); owner.trigger( 'uploadError', file, type ); owner.trigger( 'uploadComplete', file ); } }); // 上传成功 tr.on( 'load', function() { var reason; // 如果非预期,转向上传出错。 if ( (reason = requestAccept()) ) { tr.trigger( 'error', reason, true ); return; } // 全部上传完成。 if ( file.remaning === 1 ) { me._finishFile( file, ret ); } else { tr.destroy(); } }); // 配置默认的上传字段。 data = $.extend( data, { id: file.id, name: file.name, type: file.type, lastModifiedDate: file.lastModifiedDate, size: file.size }); block.chunks > 1 && $.extend( data, { chunks: block.chunks, chunk: block.chunk }); // 在发送之间可以添加字段什么的。。。 // 如果默认的字段不够使用,可以通过监听此事件来扩展 owner.trigger( 'uploadBeforeSend', block, data, headers ); // 开始发送。 tr.appendBlob( opts.fileVal, block.blob, file.name ); tr.append( data ); tr.setRequestHeader( headers ); tr.send(); }, // 完成上传。 _finishFile: function( file, ret, hds ) { var owner = this.owner; return owner .request( 'after-send-file', arguments, function() { file.setStatus( Status.COMPLETE ); owner.trigger( 'uploadSuccess', file, ret, hds ); }) .fail(function( reason ) { // 如果外部已经标记为invalid什么的,不再改状态。 if ( file.getStatus() === Status.PROGRESS ) { file.setStatus( Status.ERROR, reason ); } owner.trigger( 'uploadError', file, reason ); }) .always(function() { owner.trigger( 'uploadComplete', file ); }); }, updateFileProgress: function(file) { var totalPercent = 0, uploaded = 0; if (!file.blocks) { return; } $.each( file.blocks, function( _, v ) { uploaded += (v.percentage || 0) * (v.end - v.start); }); totalPercent = uploaded / file.size; this.owner.trigger( 'uploadProgress', file, totalPercent || 0 ); } }); }); /** * @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。 * * 如果您不想要启用此功能,请在打包的时候去掉 log 模块。 * * 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。 * * 如: * WebUploader.create({ * ... * * disableWidgets: 'log', * * ... * }) */ define('widgets/log',[ 'base', 'uploader', 'widgets/widget' ], function( Base, Uploader ) { var $ = Base.$, logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??', product = (location.hostname || location.host || 'protected').toLowerCase(), // 只针对 baidu 内部产品用户做统计功能。 enable = product && /baidu/i.exec(product), base; if (!enable) { return; } base = { dv: 3, master: 'webuploader', online: /test/.exec(product) ? 0 : 1, module: '', product: product, type: 0 }; function send(data) { var obj = $.extend({}, base, data), url = logUrl.replace(/^(.*)\?/, '$1' + $.param( obj )), image = new Image(); image.src = url; } return Uploader.register({ name: 'log', init: function() { var owner = this.owner, count = 0, size = 0; owner .on('error', function(code) { send({ type: 2, c_error_code: code }); }) .on('uploadError', function(file, reason) { send({ type: 2, c_error_code: 'UPLOAD_ERROR', c_reason: '' + reason }); }) .on('uploadComplete', function(file) { count++; size += file.size; }). on('uploadFinished', function() { send({ c_count: count, c_size: size }); count = size = 0; }); send({ c_usage: 1 }); } }); }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/compbase',[],function() { function CompBase( owner, runtime ) { this.owner = owner; this.options = owner.options; this.getRuntime = function() { return runtime; }; this.getRuid = function() { return runtime.uid; }; this.trigger = function() { return owner.trigger.apply( owner, arguments ); }; } return CompBase; }); /** * @fileOverview Html5Runtime */ define('runtime/html5/runtime',[ 'base', 'runtime/runtime', 'runtime/compbase' ], function( Base, Runtime, CompBase ) { var type = 'html5', components = {}; function Html5Runtime() { var pool = {}, me = this, destroy = this.destroy; Runtime.apply( me, arguments ); me.type = type; // 这个方法的调用者,实际上是RuntimeClient me.exec = function( comp, fn/*, args...*/) { var client = this, uid = client.uid, args = Base.slice( arguments, 2 ), instance; if ( components[ comp ] ) { instance = pool[ uid ] = pool[ uid ] || new components[ comp ]( client, me ); if ( instance[ fn ] ) { return instance[ fn ].apply( instance, args ); } } }; me.destroy = function() { return destroy && destroy.apply( this, arguments ); }; } Base.inherits( Runtime, { constructor: Html5Runtime, // 不需要连接其他程序,直接执行callback init: function() { var me = this; setTimeout(function() { me.trigger('ready'); }, 1 ); } }); // 注册Components Html5Runtime.register = function( name, component ) { var klass = components[ name ] = Base.inherits( CompBase, component ); return klass; }; // 注册html5运行时。 // 只有在支持的前提下注册。 if ( window.Blob && window.FileReader && window.DataView ) { Runtime.addRuntime( type, Html5Runtime ); } return Html5Runtime; }); /** * @fileOverview Blob Html实现 */ define('runtime/html5/blob',[ 'runtime/html5/runtime', 'lib/blob' ], function( Html5Runtime, Blob ) { return Html5Runtime.register( 'Blob', { slice: function( start, end ) { var blob = this.owner.source, slice = blob.slice || blob.webkitSlice || blob.mozSlice; blob = slice.call( blob, start, end ); return new Blob( this.getRuid(), blob ); } }); }); /** * @fileOverview FilePicker */ define('runtime/html5/filepicker',[ 'base', 'runtime/html5/runtime' ], function( Base, Html5Runtime ) { var $ = Base.$; return Html5Runtime.register( 'FilePicker', { init: function() { var container = this.getRuntime().getContainer(), me = this, owner = me.owner, opts = me.options, label = this.label = $( document.createElement('label') ), input = this.input = $( document.createElement('input') ), arr, i, len, mouseHandler; input.attr( 'type', 'file' ); input.attr( 'name', opts.name ); input.addClass('webuploader-element-invisible'); label.on( 'click', function() { input.trigger('click'); }); label.css({ opacity: 0, width: '100%', height: '100%', display: 'block', cursor: 'pointer', background: '#ffffff' }); if ( opts.multiple ) { input.attr( 'multiple', 'multiple' ); } if ( opts.accept && opts.accept.length > 0 ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { arr.push( opts.accept[ i ].mimeTypes ); } input.attr( 'accept', arr.join(',') ); } container.append( input ); container.append( label ); mouseHandler = function( e ) { owner.trigger( e.type ); }; input.on( 'change', function( e ) { var fn = arguments.callee, clone; me.files = e.target.files; // reset input clone = this.cloneNode( true ); clone.value = null; this.parentNode.replaceChild( clone, this ); input.off(); input = $( clone ).on( 'change', fn ) .on( 'mouseenter mouseleave', mouseHandler ); owner.trigger('change'); }); label.on( 'mouseenter mouseleave', mouseHandler ); }, getFiles: function() { return this.files; }, destroy: function() { this.input.off(); this.label.off(); } }); }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/util',[ 'base' ], function( Base ) { var urlAPI = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL, createObjectURL = Base.noop, revokeObjectURL = createObjectURL; if ( urlAPI ) { // 更安全的方式调用,比如android里面就能把context改成其他的对象。 createObjectURL = function() { return urlAPI.createObjectURL.apply( urlAPI, arguments ); }; revokeObjectURL = function() { return urlAPI.revokeObjectURL.apply( urlAPI, arguments ); }; } return { createObjectURL: createObjectURL, revokeObjectURL: revokeObjectURL, dataURL2Blob: function( dataURI ) { var byteStr, intArray, ab, i, mimetype, parts; parts = dataURI.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { byteStr = atob( parts[ 1 ] ); } else { byteStr = decodeURIComponent( parts[ 1 ] ); } ab = new ArrayBuffer( byteStr.length ); intArray = new Uint8Array( ab ); for ( i = 0; i < byteStr.length; i++ ) { intArray[ i ] = byteStr.charCodeAt( i ); } mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ]; return this.arrayBufferToBlob( ab, mimetype ); }, dataURL2ArrayBuffer: function( dataURI ) { var byteStr, intArray, i, parts; parts = dataURI.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { byteStr = atob( parts[ 1 ] ); } else { byteStr = decodeURIComponent( parts[ 1 ] ); } intArray = new Uint8Array( byteStr.length ); for ( i = 0; i < byteStr.length; i++ ) { intArray[ i ] = byteStr.charCodeAt( i ); } return intArray.buffer; }, arrayBufferToBlob: function( buffer, type ) { var builder = window.BlobBuilder || window.WebKitBlobBuilder, bb; // android不支持直接new Blob, 只能借助blobbuilder. if ( builder ) { bb = new builder(); bb.append( buffer ); return bb.getBlob( type ); } return new Blob([ buffer ], type ? { type: type } : {} ); }, // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg. // 你得到的结果是png. canvasToDataUrl: function( canvas, type, quality ) { return canvas.toDataURL( type, quality / 100 ); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 parseMeta: function( blob, callback ) { callback( false, {}); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 updateImageHead: function( data ) { return data; } }; }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/imagemeta',[ 'runtime/html5/util' ], function( Util ) { var api; api = { parsers: { 0xffe1: [] }, maxMetaDataSize: 262144, parse: function( blob, cb ) { var me = this, fr = new FileReader(); fr.onload = function() { cb( false, me._parse( this.result ) ); fr = fr.onload = fr.onerror = null; }; fr.onerror = function( e ) { cb( e.message ); fr = fr.onload = fr.onerror = null; }; blob = blob.slice( 0, me.maxMetaDataSize ); fr.readAsArrayBuffer( blob.getSource() ); }, _parse: function( buffer, noParse ) { if ( buffer.byteLength < 6 ) { return; } var dataview = new DataView( buffer ), offset = 2, maxOffset = dataview.byteLength - 4, headLength = offset, ret = {}, markerBytes, markerLength, parsers, i; if ( dataview.getUint16( 0 ) === 0xffd8 ) { while ( offset < maxOffset ) { markerBytes = dataview.getUint16( offset ); if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef || markerBytes === 0xfffe ) { markerLength = dataview.getUint16( offset + 2 ) + 2; if ( offset + markerLength > dataview.byteLength ) { break; } parsers = api.parsers[ markerBytes ]; if ( !noParse && parsers ) { for ( i = 0; i < parsers.length; i += 1 ) { parsers[ i ].call( api, dataview, offset, markerLength, ret ); } } offset += markerLength; headLength = offset; } else { break; } } if ( headLength > 6 ) { if ( buffer.slice ) { ret.imageHead = buffer.slice( 2, headLength ); } else { // Workaround for IE10, which does not yet // support ArrayBuffer.slice: ret.imageHead = new Uint8Array( buffer ) .subarray( 2, headLength ); } } } return ret; }, updateImageHead: function( buffer, head ) { var data = this._parse( buffer, true ), buf1, buf2, bodyoffset; bodyoffset = 2; if ( data.imageHead ) { bodyoffset = 2 + data.imageHead.byteLength; } if ( buffer.slice ) { buf2 = buffer.slice( bodyoffset ); } else { buf2 = new Uint8Array( buffer ).subarray( bodyoffset ); } buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength ); buf1[ 0 ] = 0xFF; buf1[ 1 ] = 0xD8; buf1.set( new Uint8Array( head ), 2 ); buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 ); return buf1.buffer; } }; Util.parseMeta = function() { return api.parse.apply( api, arguments ); }; Util.updateImageHead = function() { return api.updateImageHead.apply( api, arguments ); }; return api; }); /** * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image * 暂时项目中只用了orientation. * * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail. * @fileOverview EXIF解析 */ // Sample // ==================================== // Make : Apple // Model : iPhone 4S // Orientation : 1 // XResolution : 72 [72/1] // YResolution : 72 [72/1] // ResolutionUnit : 2 // Software : QuickTime 7.7.1 // DateTime : 2013:09:01 22:53:55 // ExifIFDPointer : 190 // ExposureTime : 0.058823529411764705 [1/17] // FNumber : 2.4 [12/5] // ExposureProgram : Normal program // ISOSpeedRatings : 800 // ExifVersion : 0220 // DateTimeOriginal : 2013:09:01 22:52:51 // DateTimeDigitized : 2013:09:01 22:52:51 // ComponentsConfiguration : YCbCr // ShutterSpeedValue : 4.058893515764426 // ApertureValue : 2.5260688216892597 [4845/1918] // BrightnessValue : -0.3126686601998395 // MeteringMode : Pattern // Flash : Flash did not fire, compulsory flash mode // FocalLength : 4.28 [107/25] // SubjectArea : [4 values] // FlashpixVersion : 0100 // ColorSpace : 1 // PixelXDimension : 2448 // PixelYDimension : 3264 // SensingMethod : One-chip color area sensor // ExposureMode : 0 // WhiteBalance : Auto white balance // FocalLengthIn35mmFilm : 35 // SceneCaptureType : Standard define('runtime/html5/imagemeta/exif',[ 'base', 'runtime/html5/imagemeta' ], function( Base, ImageMeta ) { var EXIF = {}; EXIF.ExifMap = function() { return this; }; EXIF.ExifMap.prototype.map = { 'Orientation': 0x0112 }; EXIF.ExifMap.prototype.get = function( id ) { return this[ id ] || this[ this.map[ id ] ]; }; EXIF.exifTagTypes = { // byte, 8-bit unsigned int: 1: { getValue: function( dataView, dataOffset ) { return dataView.getUint8( dataOffset ); }, size: 1 }, // ascii, 8-bit byte: 2: { getValue: function( dataView, dataOffset ) { return String.fromCharCode( dataView.getUint8( dataOffset ) ); }, size: 1, ascii: true }, // short, 16 bit int: 3: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint16( dataOffset, littleEndian ); }, size: 2 }, // long, 32 bit int: 4: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint32( dataOffset, littleEndian ); }, size: 4 }, // rational = two long values, // first is numerator, second is denominator: 5: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint32( dataOffset, littleEndian ) / dataView.getUint32( dataOffset + 4, littleEndian ); }, size: 8 }, // slong, 32 bit signed int: 9: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getInt32( dataOffset, littleEndian ); }, size: 4 }, // srational, two slongs, first is numerator, second is denominator: 10: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getInt32( dataOffset, littleEndian ) / dataView.getInt32( dataOffset + 4, littleEndian ); }, size: 8 } }; // undefined, 8-bit byte, value depending on field: EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ]; EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length, littleEndian ) { var tagType = EXIF.exifTagTypes[ type ], tagSize, dataOffset, values, i, str, c; if ( !tagType ) { Base.log('Invalid Exif data: Invalid tag type.'); return; } tagSize = tagType.size * length; // Determine if the value is contained in the dataOffset bytes, // or if the value at the dataOffset is a pointer to the actual data: dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8, littleEndian ) : (offset + 8); if ( dataOffset + tagSize > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid data offset.'); return; } if ( length === 1 ) { return tagType.getValue( dataView, dataOffset, littleEndian ); } values = []; for ( i = 0; i < length; i += 1 ) { values[ i ] = tagType.getValue( dataView, dataOffset + i * tagType.size, littleEndian ); } if ( tagType.ascii ) { str = ''; // Concatenate the chars: for ( i = 0; i < values.length; i += 1 ) { c = values[ i ]; // Ignore the terminating NULL byte(s): if ( c === '\u0000' ) { break; } str += c; } return str; } return values; }; EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian, data ) { var tag = dataView.getUint16( offset, littleEndian ); data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset, dataView.getUint16( offset + 2, littleEndian ), // tag type dataView.getUint32( offset + 4, littleEndian ), // tag length littleEndian ); }; EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset, littleEndian, data ) { var tagsNumber, dirEndOffset, i; if ( dirOffset + 6 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid directory offset.'); return; } tagsNumber = dataView.getUint16( dirOffset, littleEndian ); dirEndOffset = dirOffset + 2 + 12 * tagsNumber; if ( dirEndOffset + 4 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid directory size.'); return; } for ( i = 0; i < tagsNumber; i += 1 ) { this.parseExifTag( dataView, tiffOffset, dirOffset + 2 + 12 * i, // tag offset littleEndian, data ); } // Return the offset to the next directory: return dataView.getUint32( dirEndOffset, littleEndian ); }; // EXIF.getExifThumbnail = function(dataView, offset, length) { // var hexData, // i, // b; // if (!length || offset + length > dataView.byteLength) { // Base.log('Invalid Exif data: Invalid thumbnail data.'); // return; // } // hexData = []; // for (i = 0; i < length; i += 1) { // b = dataView.getUint8(offset + i); // hexData.push((b < 16 ? '0' : '') + b.toString(16)); // } // return 'data:image/jpeg,%' + hexData.join('%'); // }; EXIF.parseExifData = function( dataView, offset, length, data ) { var tiffOffset = offset + 10, littleEndian, dirOffset; // Check for the ASCII code for "Exif" (0x45786966): if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) { // No Exif data, might be XMP data instead return; } if ( tiffOffset + 8 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid segment size.'); return; } // Check for the two null bytes: if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) { Base.log('Invalid Exif data: Missing byte alignment offset.'); return; } // Check the byte alignment: switch ( dataView.getUint16( tiffOffset ) ) { case 0x4949: littleEndian = true; break; case 0x4D4D: littleEndian = false; break; default: Base.log('Invalid Exif data: Invalid byte alignment marker.'); return; } // Check for the TIFF tag marker (0x002A): if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) { Base.log('Invalid Exif data: Missing TIFF marker.'); return; } // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal: dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian ); // Create the exif object to store the tags: data.exif = new EXIF.ExifMap(); // Parse the tags of the main image directory and retrieve the // offset to the next directory, usually the thumbnail directory: dirOffset = EXIF.parseExifTags( dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data ); // 尝试读取缩略图 // if ( dirOffset ) { // thumbnailData = {exif: {}}; // dirOffset = EXIF.parseExifTags( // dataView, // tiffOffset, // tiffOffset + dirOffset, // littleEndian, // thumbnailData // ); // // Check for JPEG Thumbnail offset: // if (thumbnailData.exif[0x0201]) { // data.exif.Thumbnail = EXIF.getExifThumbnail( // dataView, // tiffOffset + thumbnailData.exif[0x0201], // thumbnailData.exif[0x0202] // Thumbnail data length // ); // } // } }; ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData ); return EXIF; }); /** * @fileOverview Image */ define('runtime/html5/image',[ 'base', 'runtime/html5/runtime', 'runtime/html5/util' ], function( Base, Html5Runtime, Util ) { var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'; return Html5Runtime.register( 'Image', { // flag: 标记是否被修改过。 modified: false, init: function() { var me = this, img = new Image(); img.onload = function() { me._info = { type: me.type, width: this.width, height: this.height }; // 读取meta信息。 if ( !me._metas && 'image/jpeg' === me.type ) { Util.parseMeta( me._blob, function( error, ret ) { me._metas = ret; me.owner.trigger('load'); }); } else { me.owner.trigger('load'); } }; img.onerror = function() { me.owner.trigger('error'); }; me._img = img; }, loadFromBlob: function( blob ) { var me = this, img = me._img; me._blob = blob; me.type = blob.type; img.src = Util.createObjectURL( blob.getSource() ); me.owner.once( 'load', function() { Util.revokeObjectURL( img.src ); }); }, resize: function( width, height ) { var canvas = this._canvas || (this._canvas = document.createElement('canvas')); this._resize( this._img, canvas, width, height ); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger( 'complete', 'resize' ); }, crop: function( x, y, w, h, s ) { var cvs = this._canvas || (this._canvas = document.createElement('canvas')), opts = this.options, img = this._img, iw = img.naturalWidth, ih = img.naturalHeight, orientation = this.getOrientation(); s = s || 1; // values that require 90 degree rotation // if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // switch ( orientation ) { // case 6: // tmp = x; // x = y; // y = iw * s - tmp - w; // console.log(ih * s, tmp, w) // break; // } // (w ^= h, h ^= w, w ^= h); // } cvs.width = w; cvs.height = h; opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation ); this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s ); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger( 'complete', 'crop' ); }, getAsBlob: function( type ) { var blob = this._blob, opts = this.options, canvas; type = type || this.type; // blob需要重新生成。 if ( this.modified || this.type !== type ) { canvas = this._canvas; if ( type === 'image/jpeg' ) { blob = Util.canvasToDataUrl( canvas, type, opts.quality ); if ( opts.preserveHeaders && this._metas && this._metas.imageHead ) { blob = Util.dataURL2ArrayBuffer( blob ); blob = Util.updateImageHead( blob, this._metas.imageHead ); blob = Util.arrayBufferToBlob( blob, type ); return blob; } } else { blob = Util.canvasToDataUrl( canvas, type ); } blob = Util.dataURL2Blob( blob ); } return blob; }, getAsDataUrl: function( type ) { var opts = this.options; type = type || this.type; if ( type === 'image/jpeg' ) { return Util.canvasToDataUrl( this._canvas, type, opts.quality ); } else { return this._canvas.toDataURL( type ); } }, getOrientation: function() { return this._metas && this._metas.exif && this._metas.exif.get('Orientation') || 1; }, info: function( val ) { // setter if ( val ) { this._info = val; return this; } // getter return this._info; }, meta: function( val ) { // setter if ( val ) { this._meta = val; return this; } // getter return this._meta; }, destroy: function() { var canvas = this._canvas; this._img.onload = null; if ( canvas ) { canvas.getContext('2d') .clearRect( 0, 0, canvas.width, canvas.height ); canvas.width = canvas.height = 0; this._canvas = null; } // 释放内存。非常重要,否则释放不了image的内存。 this._img.src = BLANK; this._img = this._blob = null; }, _resize: function( img, cvs, width, height ) { var opts = this.options, naturalWidth = img.width, naturalHeight = img.height, orientation = this.getOrientation(), scale, w, h, x, y; // values that require 90 degree rotation if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // 交换width, height的值。 width ^= height; height ^= width; width ^= height; } scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth, height / naturalHeight ); // 不允许放大。 opts.allowMagnify || (scale = Math.min( 1, scale )); w = naturalWidth * scale; h = naturalHeight * scale; if ( opts.crop ) { cvs.width = width; cvs.height = height; } else { cvs.width = w; cvs.height = h; } x = (cvs.width - w) / 2; y = (cvs.height - h) / 2; opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation ); this._renderImageToCanvas( cvs, img, x, y, w, h ); }, _rotate2Orientaion: function( canvas, orientation ) { var width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d'); switch ( orientation ) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; } switch ( orientation ) { case 2: // horizontal flip ctx.translate( width, 0 ); ctx.scale( -1, 1 ); break; case 3: // 180 rotate left ctx.translate( width, height ); ctx.rotate( Math.PI ); break; case 4: // vertical flip ctx.translate( 0, height ); ctx.scale( 1, -1 ); break; case 5: // vertical flip + 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.scale( 1, -1 ); break; case 6: // 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.translate( 0, -height ); break; case 7: // horizontal flip + 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.translate( width, -height ); ctx.scale( -1, 1 ); break; case 8: // 90 rotate left ctx.rotate( -0.5 * Math.PI ); ctx.translate( -width, 0 ); break; } }, // https://github.com/stomita/ios-imagefile-megapixel/ // blob/master/src/megapix-image.js _renderImageToCanvas: (function() { // 如果不是ios, 不需要这么复杂! if ( !Base.os.ios ) { return function( canvas ) { var args = Base.slice( arguments, 1 ), ctx = canvas.getContext('2d'); ctx.drawImage.apply( ctx, args ); }; } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into * canvas for some images. */ function detectVerticalSquash( img, iw, ih ) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), sy = 0, ey = ih, py = ih, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx.drawImage( img, 0, 0 ); data = ctx.getImageData( 0, 0, 1, ih ).data; // search image edge pixel position in case // it is squashed vertically. while ( py > sy ) { alpha = data[ (py - 1) * 4 + 3 ]; if ( alpha === 0 ) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } // fix ie7 bug // http://stackoverflow.com/questions/11929099/ // html5-canvas-drawimage-ratio-bug-ios if ( Base.os.ios >= 7 ) { return function( canvas, img, x, y, w, h ) { var iw = img.naturalWidth, ih = img.naturalHeight, vertSquashRatio = detectVerticalSquash( img, iw, ih ); return canvas.getContext('2d').drawImage( img, 0, 0, iw * vertSquashRatio, ih * vertSquashRatio, x, y, w, h ); }; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be * subsampled in rendering. */ function detectSubsampling( img ) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas, ctx; // subsampling may happen overmegapixel image if ( iw * ih > 1024 * 1024 ) { canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; ctx = canvas.getContext('2d'); ctx.drawImage( img, -iw + 1, 0 ); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering // edge pixel or not. if alpha value is 0 // image is not covering, hence subsampled. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0; } else { return false; } } return function( canvas, img, x, y, width, height ) { var iw = img.naturalWidth, ih = img.naturalHeight, ctx = canvas.getContext('2d'), subsampled = detectSubsampling( img ), doSquash = this.type === 'image/jpeg', d = 1024, sy = 0, dy = 0, tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx; if ( subsampled ) { iw /= 2; ih /= 2; } ctx.save(); tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext('2d'); vertSquashRatio = doSquash ? detectVerticalSquash( img, iw, ih ) : 1; dw = Math.ceil( d * width / iw ); dh = Math.ceil( d * height / ih / vertSquashRatio ); while ( sy < ih ) { sx = 0; dx = 0; while ( sx < iw ) { tmpCtx.clearRect( 0, 0, d, d ); tmpCtx.drawImage( img, -sx, -sy ); ctx.drawImage( tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh ); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }; })() }); }); /** * 这个方式性能不行,但是可以解决android里面的toDataUrl的bug * android里面toDataUrl('image/jpege')得到的结果却是png. * * 所以这里没辙,只能借助这个工具 * @fileOverview jpeg encoder */ define('runtime/html5/jpegencoder',[], function( require, exports, module ) { /* Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009 Basic GUI blocking jpeg encoder */ function JPEGEncoder(quality) { var self = this; var fround = Math.round; var ffloor = Math.floor; var YTable = new Array(64); var UVTable = new Array(64); var fdtbl_Y = new Array(64); var fdtbl_UV = new Array(64); var YDC_HT; var UVDC_HT; var YAC_HT; var UVAC_HT; var bitcode = new Array(65535); var category = new Array(65535); var outputfDCTQuant = new Array(64); var DU = new Array(64); var byteout = []; var bytenew = 0; var bytepos = 7; var YDU = new Array(64); var UDU = new Array(64); var VDU = new Array(64); var clt = new Array(256); var RGB_YUV_TABLE = new Array(2048); var currentQuality; var ZigZag = [ 0, 1, 5, 6,14,15,27,28, 2, 4, 7,13,16,26,29,42, 3, 8,12,17,25,30,41,43, 9,11,18,24,31,40,44,53, 10,19,23,32,39,45,52,54, 20,22,33,38,46,51,55,60, 21,34,37,47,50,56,59,61, 35,36,48,49,57,58,62,63 ]; var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0]; var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d]; var std_ac_luminance_values = [ 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12, 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07, 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0, 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16, 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39, 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49, 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69, 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79, 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98, 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7, 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5, 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4, 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea, 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, 0xf9,0xfa ]; var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0]; var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77]; var std_ac_chrominance_values = [ 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21, 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0, 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34, 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38, 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48, 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68, 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78, 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96, 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5, 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3, 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2, 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9, 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, 0xf9,0xfa ]; function initQuantTables(sf){ var YQT = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68,109,103, 77, 24, 35, 55, 64, 81,104,113, 92, 49, 64, 78, 87,103,121,120,101, 72, 92, 95, 98,112,100,103, 99 ]; for (var i = 0; i < 64; i++) { var t = ffloor((YQT[i]*sf+50)/100); if (t < 1) { t = 1; } else if (t > 255) { t = 255; } YTable[ZigZag[i]] = t; } var UVQT = [ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 ]; for (var j = 0; j < 64; j++) { var u = ffloor((UVQT[j]*sf+50)/100); if (u < 1) { u = 1; } else if (u > 255) { u = 255; } UVTable[ZigZag[j]] = u; } var aasf = [ 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 ]; var k = 0; for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); k++; } } } function computeHuffmanTbl(nrcodes, std_table){ var codevalue = 0; var pos_in_table = 0; var HT = new Array(); for (var k = 1; k <= 16; k++) { for (var j = 1; j <= nrcodes[k]; j++) { HT[std_table[pos_in_table]] = []; HT[std_table[pos_in_table]][0] = codevalue; HT[std_table[pos_in_table]][1] = k; pos_in_table++; codevalue++; } codevalue*=2; } return HT; } function initHuffmanTbl() { YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values); UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values); YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values); UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values); } function initCategoryNumber() { var nrlower = 1; var nrupper = 2; for (var cat = 1; cat <= 15; cat++) { //Positive numbers for (var nr = nrlower; nr<nrupper; nr++) { category[32767+nr] = cat; bitcode[32767+nr] = []; bitcode[32767+nr][1] = cat; bitcode[32767+nr][0] = nr; } //Negative numbers for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) { category[32767+nrneg] = cat; bitcode[32767+nrneg] = []; bitcode[32767+nrneg][1] = cat; bitcode[32767+nrneg][0] = nrupper-1+nrneg; } nrlower <<= 1; nrupper <<= 1; } } function initRGBYUVTable() { for(var i = 0; i < 256;i++) { RGB_YUV_TABLE[i] = 19595 * i; RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i; RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000; RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i; RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i; RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF; RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i; RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i; } } // IO functions function writeBits(bs) { var value = bs[0]; var posval = bs[1]-1; while ( posval >= 0 ) { if (value & (1 << posval) ) { bytenew |= (1 << bytepos); } posval--; bytepos--; if (bytepos < 0) { if (bytenew == 0xFF) { writeByte(0xFF); writeByte(0); } else { writeByte(bytenew); } bytepos=7; bytenew=0; } } } function writeByte(value) { byteout.push(clt[value]); // write char directly instead of converting later } function writeWord(value) { writeByte((value>>8)&0xFF); writeByte((value )&0xFF); } // DCT & quantization core function fDCTQuant(data, fdtbl) { var d0, d1, d2, d3, d4, d5, d6, d7; /* Pass 1: process rows. */ var dataOff=0; var i; var I8 = 8; var I64 = 64; for (i=0; i<I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff+1]; d2 = data[dataOff+2]; d3 = data[dataOff+3]; d4 = data[dataOff+4]; d5 = data[dataOff+5]; d6 = data[dataOff+6]; d7 = data[dataOff+7]; var tmp0 = d0 + d7; var tmp7 = d0 - d7; var tmp1 = d1 + d6; var tmp6 = d1 - d6; var tmp2 = d2 + d5; var tmp5 = d2 - d5; var tmp3 = d3 + d4; var tmp4 = d3 - d4; /* Even part */ var tmp10 = tmp0 + tmp3; /* phase 2 */ var tmp13 = tmp0 - tmp3; var tmp11 = tmp1 + tmp2; var tmp12 = tmp1 - tmp2; data[dataOff] = tmp10 + tmp11; /* phase 3 */ data[dataOff+4] = tmp10 - tmp11; var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */ data[dataOff+2] = tmp13 + z1; /* phase 5 */ data[dataOff+6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */ var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */ var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */ var z3 = tmp11 * 0.707106781; /* c4 */ var z11 = tmp7 + z3; /* phase 5 */ var z13 = tmp7 - z3; data[dataOff+5] = z13 + z2; /* phase 6 */ data[dataOff+3] = z13 - z2; data[dataOff+1] = z11 + z4; data[dataOff+7] = z11 - z4; dataOff += 8; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataOff = 0; for (i=0; i<I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 8]; d2 = data[dataOff + 16]; d3 = data[dataOff + 24]; d4 = data[dataOff + 32]; d5 = data[dataOff + 40]; d6 = data[dataOff + 48]; d7 = data[dataOff + 56]; var tmp0p2 = d0 + d7; var tmp7p2 = d0 - d7; var tmp1p2 = d1 + d6; var tmp6p2 = d1 - d6; var tmp2p2 = d2 + d5; var tmp5p2 = d2 - d5; var tmp3p2 = d3 + d4; var tmp4p2 = d3 - d4; /* Even part */ var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */ var tmp13p2 = tmp0p2 - tmp3p2; var tmp11p2 = tmp1p2 + tmp2p2; var tmp12p2 = tmp1p2 - tmp2p2; data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */ data[dataOff+32] = tmp10p2 - tmp11p2; var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */ data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */ data[dataOff+48] = tmp13p2 - z1p2; /* Odd part */ tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */ tmp11p2 = tmp5p2 + tmp6p2; tmp12p2 = tmp6p2 + tmp7p2; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */ var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */ var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */ var z3p2 = tmp11p2 * 0.707106781; /* c4 */ var z11p2 = tmp7p2 + z3p2; /* phase 5 */ var z13p2 = tmp7p2 - z3p2; data[dataOff+40] = z13p2 + z2p2; /* phase 6 */ data[dataOff+24] = z13p2 - z2p2; data[dataOff+ 8] = z11p2 + z4p2; data[dataOff+56] = z11p2 - z4p2; dataOff++; /* advance pointer to next column */ } // Quantize/descale the coefficients var fDCTQuant; for (i=0; i<I64; ++i) { // Apply the quantization and scaling factor & Round to nearest integer fDCTQuant = data[i]*fdtbl[i]; outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0); //outputfDCTQuant[i] = fround(fDCTQuant); } return outputfDCTQuant; } function writeAPP0() { writeWord(0xFFE0); // marker writeWord(16); // length writeByte(0x4A); // J writeByte(0x46); // F writeByte(0x49); // I writeByte(0x46); // F writeByte(0); // = "JFIF",'\0' writeByte(1); // versionhi writeByte(1); // versionlo writeByte(0); // xyunits writeWord(1); // xdensity writeWord(1); // ydensity writeByte(0); // thumbnwidth writeByte(0); // thumbnheight } function writeSOF0(width, height) { writeWord(0xFFC0); // marker writeWord(17); // length, truecolor YUV JPG writeByte(8); // precision writeWord(height); writeWord(width); writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0x11); // HVY writeByte(0); // QTY writeByte(2); // IdU writeByte(0x11); // HVU writeByte(1); // QTU writeByte(3); // IdV writeByte(0x11); // HVV writeByte(1); // QTV } function writeDQT() { writeWord(0xFFDB); // marker writeWord(132); // length writeByte(0); for (var i=0; i<64; i++) { writeByte(YTable[i]); } writeByte(1); for (var j=0; j<64; j++) { writeByte(UVTable[j]); } } function writeDHT() { writeWord(0xFFC4); // marker writeWord(0x01A2); // length writeByte(0); // HTYDCinfo for (var i=0; i<16; i++) { writeByte(std_dc_luminance_nrcodes[i+1]); } for (var j=0; j<=11; j++) { writeByte(std_dc_luminance_values[j]); } writeByte(0x10); // HTYACinfo for (var k=0; k<16; k++) { writeByte(std_ac_luminance_nrcodes[k+1]); } for (var l=0; l<=161; l++) { writeByte(std_ac_luminance_values[l]); } writeByte(1); // HTUDCinfo for (var m=0; m<16; m++) { writeByte(std_dc_chrominance_nrcodes[m+1]); } for (var n=0; n<=11; n++) { writeByte(std_dc_chrominance_values[n]); } writeByte(0x11); // HTUACinfo for (var o=0; o<16; o++) { writeByte(std_ac_chrominance_nrcodes[o+1]); } for (var p=0; p<=161; p++) { writeByte(std_ac_chrominance_values[p]); } } function writeSOS() { writeWord(0xFFDA); // marker writeWord(12); // length writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0); // HTY writeByte(2); // IdU writeByte(0x11); // HTU writeByte(3); // IdV writeByte(0x11); // HTV writeByte(0); // Ss writeByte(0x3f); // Se writeByte(0); // Bf } function processDU(CDU, fdtbl, DC, HTDC, HTAC){ var EOB = HTAC[0x00]; var M16zeroes = HTAC[0xF0]; var pos; var I16 = 16; var I63 = 63; var I64 = 64; var DU_DCT = fDCTQuant(CDU, fdtbl); //ZigZag reorder for (var j=0;j<I64;++j) { DU[ZigZag[j]]=DU_DCT[j]; } var Diff = DU[0] - DC; DC = DU[0]; //Encode DC if (Diff==0) { writeBits(HTDC[0]); // Diff might be 0 } else { pos = 32767+Diff; writeBits(HTDC[category[pos]]); writeBits(bitcode[pos]); } //Encode ACs var end0pos = 63; // was const... which is crazy for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {}; //end0pos = first element in reverse order !=0 if ( end0pos == 0) { writeBits(EOB); return DC; } var i = 1; var lng; while ( i <= end0pos ) { var startpos = i; for (; (DU[i]==0) && (i<=end0pos); ++i) {} var nrzeroes = i-startpos; if ( nrzeroes >= I16 ) { lng = nrzeroes>>4; for (var nrmarker=1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes); nrzeroes = nrzeroes&0xF; } pos = 32767+DU[i]; writeBits(HTAC[(nrzeroes<<4)+category[pos]]); writeBits(bitcode[pos]); i++; } if ( end0pos != I63 ) { writeBits(EOB); } return DC; } function initCharLookupTable(){ var sfcc = String.fromCharCode; for(var i=0; i < 256; i++){ ///// ACHTUNG // 255 clt[i] = sfcc(i); } } this.encode = function(image,quality) // image data object { // var time_start = new Date().getTime(); if(quality) setQuality(quality); // Initialize bit writer byteout = new Array(); bytenew=0; bytepos=7; // Add JPEG headers writeWord(0xFFD8); // SOI writeAPP0(); writeDQT(); writeSOF0(image.width,image.height); writeDHT(); writeSOS(); // Encode 8x8 macroblocks var DCY=0; var DCU=0; var DCV=0; bytenew=0; bytepos=7; this.encode.displayName = "_encode_"; var imageData = image.data; var width = image.width; var height = image.height; var quadWidth = width*4; var tripleWidth = width*3; var x, y = 0; var r, g, b; var start,p, col,row,pos; while(y < height){ x = 0; while(x < quadWidth){ start = quadWidth * y + x; p = start; col = -1; row = 0; for(pos=0; pos < 64; pos++){ row = pos >> 3;// /8 col = ( pos & 7 ) * 4; // %8 p = start + ( row * quadWidth ) + col; if(y+row >= height){ // padding bottom p-= (quadWidth*(y+1+row-height)); } if(x+col >= quadWidth){ // padding right p-= ((x+col) - quadWidth +4) } r = imageData[ p++ ]; g = imageData[ p++ ]; b = imageData[ p++ ]; /* // calculate YUV values dynamically YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80 UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b)); VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b)); */ // use lookup table (slightly faster) YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128; UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128; VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128; } DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); x+=32; } y+=8; } //////////////////////////////////////////////////////////////// // Do the bit alignment of the EOI marker if ( bytepos >= 0 ) { var fillbits = []; fillbits[1] = bytepos+1; fillbits[0] = (1<<(bytepos+1))-1; writeBits(fillbits); } writeWord(0xFFD9); //EOI var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join('')); byteout = []; // benchmarking // var duration = new Date().getTime() - time_start; // console.log('Encoding time: '+ currentQuality + 'ms'); // return jpegDataUri } function setQuality(quality){ if (quality <= 0) { quality = 1; } if (quality > 100) { quality = 100; } if(currentQuality == quality) return // don't recalc if unchanged var sf = 0; if (quality < 50) { sf = Math.floor(5000 / quality); } else { sf = Math.floor(200 - quality*2); } initQuantTables(sf); currentQuality = quality; // console.log('Quality set to: '+quality +'%'); } function init(){ // var time_start = new Date().getTime(); if(!quality) quality = 50; // Create tables initCharLookupTable() initHuffmanTbl(); initCategoryNumber(); initRGBYUVTable(); setQuality(quality); // var duration = new Date().getTime() - time_start; // console.log('Initialization '+ duration + 'ms'); } init(); }; JPEGEncoder.encode = function( data, quality ) { var encoder = new JPEGEncoder( quality ); return encoder.encode( data ); } return JPEGEncoder; }); /** * @fileOverview Fix android canvas.toDataUrl bug. */ define('runtime/html5/androidpatch',[ 'runtime/html5/util', 'runtime/html5/jpegencoder', 'base' ], function( Util, encoder, Base ) { var origin = Util.canvasToDataUrl, supportJpeg; Util.canvasToDataUrl = function( canvas, type, quality ) { var ctx, w, h, fragement, parts; // 非android手机直接跳过。 if ( !Base.os.android ) { return origin.apply( null, arguments ); } // 检测是否canvas支持jpeg导出,根据数据格式来判断。 // JPEG 前两位分别是:255, 216 if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) { fragement = origin.apply( null, arguments ); parts = fragement.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { fragement = atob( parts[ 1 ] ); } else { fragement = decodeURIComponent( parts[ 1 ] ); } fragement = fragement.substring( 0, 2 ); supportJpeg = fragement.charCodeAt( 0 ) === 255 && fragement.charCodeAt( 1 ) === 216; } // 只有在android环境下才修复 if ( type === 'image/jpeg' && !supportJpeg ) { w = canvas.width; h = canvas.height; ctx = canvas.getContext('2d'); return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality ); } return origin.apply( null, arguments ); }; }); /** * @fileOverview Transport * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分, * 而不需要重头再传一次。另外断点续传也需要用chunked方式。 */ define('runtime/html5/transport',[ 'base', 'runtime/html5/runtime' ], function( Base, Html5Runtime ) { var noop = Base.noop, $ = Base.$; return Html5Runtime.register( 'Transport', { init: function() { this._status = 0; this._response = null; }, send: function() { var owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server, formData, binary, fr; if ( opts.sendAsBinary ) { server += (/\?/.test( server ) ? '&' : '?') + $.param( owner._formData ); binary = blob.getSource(); } else { formData = new FormData(); $.each( owner._formData, function( k, v ) { formData.append( k, v ); }); formData.append( opts.fileVal, blob.getSource(), opts.filename || owner._formData.name || '' ); } if ( opts.withCredentials && 'withCredentials' in xhr ) { xhr.open( opts.method, server, true ); xhr.withCredentials = true; } else { xhr.open( opts.method, server ); } this._setRequestHeader( xhr, opts.headers ); if ( binary ) { // 强制设置成 content-type 为文件流。 xhr.overrideMimeType && xhr.overrideMimeType('application/octet-stream'); // android直接发送blob会导致服务端接收到的是空文件。 // bug详情。 // https://code.google.com/p/android/issues/detail?id=39882 // 所以先用fileReader读取出来再通过arraybuffer的方式发送。 if ( Base.os.android ) { fr = new FileReader(); fr.onload = function() { xhr.send( this.result ); fr = fr.onload = null; }; fr.readAsArrayBuffer( binary ); } else { xhr.send( binary ); } } else { xhr.send( formData ); } }, getResponse: function() { return this._response; }, getResponseAsJson: function() { return this._parseJson( this._response ); }, getStatus: function() { return this._status; }, abort: function() { var xhr = this._xhr; if ( xhr ) { xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; xhr.abort(); this._xhr = xhr = null; } }, destroy: function() { this.abort(); }, _initAjax: function() { var me = this, xhr = new XMLHttpRequest(), opts = this.options; if ( opts.withCredentials && !('withCredentials' in xhr) && typeof XDomainRequest !== 'undefined' ) { xhr = new XDomainRequest(); } xhr.upload.onprogress = function( e ) { var percentage = 0; if ( e.lengthComputable ) { percentage = e.loaded / e.total; } return me.trigger( 'progress', percentage ); }; xhr.onreadystatechange = function() { if ( xhr.readyState !== 4 ) { return; } xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; me._xhr = null; me._status = xhr.status; if ( xhr.status >= 200 && xhr.status < 300 ) { me._response = xhr.responseText; return me.trigger('load'); } else if ( xhr.status >= 500 && xhr.status < 600 ) { me._response = xhr.responseText; return me.trigger( 'error', 'server' ); } return me.trigger( 'error', me._status ? 'http' : 'abort' ); }; me._xhr = xhr; return xhr; }, _setRequestHeader: function( xhr, headers ) { $.each( headers, function( key, val ) { xhr.setRequestHeader( key, val ); }); }, _parseJson: function( str ) { var json; try { json = JSON.parse( str ); } catch ( ex ) { json = {}; } return json; } }); }); define('webuploader',[ 'base', 'widgets/filepicker', 'widgets/image', 'widgets/queue', 'widgets/runtime', 'widgets/upload', 'widgets/log', 'runtime/html5/blob', 'runtime/html5/filepicker', 'runtime/html5/imagemeta/exif', 'runtime/html5/image', 'runtime/html5/androidpatch', 'runtime/html5/transport' ], function( Base ) { return Base; }); return require('webuploader'); });
// Last updated April 28, 2019. var SHOPIFY_APPS = [ { name: 'Fera.ai', // Keep this under 20 characters short_description: 'Customer reviews, photos, counters, events, etc', // Keep this under 75 characters long_description: 'Collect and grow your customer reviews, photos, videos, testimonials, and more.', app_store_url: 'https://apps.shopify.com/fera', website_url: "https://www.fera.ai", script_pattern: /cdn\.fera\.ai|bananastand\.js|fera\.js/, category: "Sales" }, { name: 'Reserve In-store', short_description: 'Let customers reserve products online for in-store pickup', app_store_url: 'https://apps.shopify.com/reserve-in-store-by-fera', website_url: "https://www.reserveinstore.com", script_pattern: /cdn\.reserveinstore\.com/, category: "Orders and shipping" }, { name: "Tawk.to", short_description: "Live chat", app_store_url: "https://apps.shopify.com/tawk-to", website_url: "https://www.tawk.to", script_pattern: "embed.tawk.to", category: "Customer service" }, { name: "Privy", short_description: "Free email popups, exit intent, targeted modals, wheels & more", app_store_url: "https://apps.shopify.com/privy", website_url: "https://www.privy.com", script_pattern: "shopify.privy.com/widget.js", category: "Marketing" }, { name: "Hextom Shipping Bar", short_description: "Free shipping bar with updated cart goal to boost order value", app_store_url: "https://apps.shopify.com/free-shipping-bar", website_url: "https://hextom.com", script_pattern: "lastsecondcoupon/js/freeshippingbar.js", category: "Marketing" }, { name: "PushOwl", short_description: "Recover Abandoned Carts via Push Notifications", app_store_url: "https://apps.shopify.com/pushowl", website_url: "https://pushowl.com", script_pattern: "sdks/pushowl-shopify.js", category: "Marketing" }, { name: "Just Uno", short_description: "Pop Ups & Social Media Marketing Platform", app_store_url: "https://apps.shopify.com/justuno-social-email-leads", website_url: "https://www.justuno.com", script_pattern: "scripttags.justuno.com", category: "Marketing" }, { name: "Shogun", short_description: "Landing Page Builder", app_store_url: "https://apps.shopify.com/shogun", website_url: "https://getshogun.com", script_pattern: "cdn.getshogun.com/pixel.js", category: "Marketing" }, { name: "Omnisend", short_description: "Email & Marketing Automation", app_store_url: "https://apps.shopify.com/omnisend", website_url: "https://www.omnisend.com", script_pattern: "inShop/Embed/shopify.js", category: "Marketing" }, { name: "Smile.io", short_description: "Loyalty Points, VIP, Referral Programs", app_store_url: "https://apps.shopify.com/smile-io", website_url: "https://smile.io", script_pattern: "smile-shopify.js", category: "Marketing" }, { name: "Smile.io", short_description: "Loyalty Points, VIP, Referral Programs", app_store_url: "https://apps.shopify.com/smile-io", website_url: "https://smile.io", script_pattern: "sweettooth.io", category: "Marketing" }, { name: "Spin‑a‑Sale", short_description: "Interactive email pop-up", app_store_url: "https://apps.shopify.com/spin-a-sale", website_url: "https://spinasale.com", script_pattern: "js/spin-v3.js", category: "Marketing" }, { name: "FireApps Ali Reviews", short_description: "Import reviews from AliExpress, Photo & Site Reviews", app_store_url: "https://apps.shopify.com/ali-reviews", website_url: "https://fireapps.io", script_pattern: "js/frontend/comment.js", category: "Marketing" }, { name: "Jilt", short_description: "Automated emails", app_store_url: "https://apps.shopify.com/jilt-cart-abandonment-solution", website_url: "https://jilt.com", script_pattern: "storefront/v1/jilt.js", category: "Marketing" }, { name: "Conversio", short_description: "Email Marketing Automation. Make every email count", app_store_url: "https://apps.shopify.com/conversio", website_url: "https://conversio.com", script_pattern: "conversio.com/scripts/shopify.js", category: "Marketing" }, { name: "Wheelio", short_description: "Gamified pop‑up", app_store_url: "https://apps.shopify.com/wheelio-first-interactive-exit-intent-pop-up", website_url: "http://wheelio.conversionpirate.com", script_pattern: "wheelio", category: "Marketing" }, { name: "MailChimp", short_description: "MailChimp list with exit intent popups and coupons", app_store_url: "https://apps.shopify.com/mailchimp-forms", website_url: "https://www.mailmunch.co", script_pattern: "a.mailmunch.co/widgets", category: "Marketing" }, { name: "PageFly", short_description: "Advanced Page Builder", app_store_url: "https://apps.shopify.com/pagefly", website_url: "https://www.sellersmith.com", script_pattern: "pagefly/assets", category: "Marketing" }, { name: "Clever Google Adwords", short_description: "Boost your marketing tactics with Google Ads by Clever Adwords", app_store_url: "https://apps.shopify.com/cleverppc", website_url: "https://www.cleverecommerce.com", script_pattern: "mc.js", category: "Marketing" }, { name: "Swell", short_description: "Rewards and Referrals", app_store_url: "https://apps.shopify.com/swell", website_url: "http://www.swellrewards.com", script_pattern: "cdn-loyalty.yotpo.com", category: "Marketing" }, { name: "Email Collection Bar", short_description: "Grow your email list with customizable bar, and boost sales", app_store_url: "https://apps.shopify.com/email-collection-bar", website_url: "https://hextom.com", script_pattern: "lastsecondcoupon/js/emailcollectionbar.js", category: "Marketing" }, { name: "Spur-i-t Popup Upsell", short_description: "Fully Customizable Popup", app_store_url: "https://apps.shopify.com/upsell-popup-on-exit-visit", website_url: "https://spur-i-t.com", script_pattern: "upsell-on-exit-visit/js/common.js", category: "Marketing" }, { name: "MailMunch", short_description: "Email Popups with Exit Intent", app_store_url: "https://apps.shopify.com/mailmunch", website_url: "https://www.mailmunch.co", script_pattern: "widgets/site-519579-1d4a0439b676bb9b4e1159635561fda7fb2c0857.js", category: "Marketing" }, { name: "Pixelpop", short_description: "Build your mailing list and boost sales with popups", app_store_url: "https://apps.shopify.com/popups-promos-banners-pixelpop", website_url: "http://pixelunion.net", script_pattern: "pixelpop.js", category: "Marketing" }, { name: "Zotabox (Multiple possibilites)", short_description: "Header Bar or easy contact form", app_store_url: "https://apps.shopify.com/partners/zotabox", website_url: "https://info.zotabox.com", script_pattern: "static.zotabox.co", category: "Marketing" }, { name: "WhatsApp Share + Chat", short_description: "Let your customer be your promoter, abandoned cart on whatsapp", app_store_url: "https://apps.shopify.com/whatsapp-sharing", website_url: "https://shopiapps.in", script_pattern: "whatsapp-share/inc/whatsapp-button.js", category: "Marketing" }, { name: "OptinMate", short_description: "Email Collection, Coupons & Social Popups, Bards & Cards", app_store_url: "https://apps.shopify.com/optinmate-2", website_url: "https://optinmate.com", script_pattern: "optinmate.com", category: "Marketing" }, { name: "Sumo", short_description: "Grow Sales & Conversio?", app_store_url: "https://apps.shopify.com/sumome", website_url: "https://sumo.com", script_pattern: "sumome-plugin/js/sumome.js", category: "Marketing" }, { name: "Refersion", short_description: "Track referrals & pay commissions to affiliates + influencers", app_store_url: "https://apps.shopify.com/refersion", website_url: "https://www.refersion.com", script_pattern: "cdn.refersion.com/pixel.js", category: "Marketing" }, { name: "Care Cart", short_description: "Recover Abandon Cart Orders by Sales & Marketing Automation", app_store_url: "https://apps.shopify.com/care-cart", website_url: "https://carecart.io", script_pattern: "api/abandoned-cart/js-script", category: "Marketing" }, { name: "RetargetApp", short_description: "Get more sales and new customers with automated Facebook ads", app_store_url: "https://apps.shopify.com/retargetapp-facebook-retargeting", website_url: "http://retargetapp.com", script_pattern: "pixel/pixel.min.js", category: "Marketing" }, { name: "Sales Rocket", short_description: "All-in-1 scarcity, urgency and social proof", app_store_url: "https://apps.shopify.com/window-shoppers", website_url: "http://www.codeinero.net", script_pattern: "Scripts/windowshoppers.min.js", category: "Marketing" }, { name: "Recart", short_description: "Facebook Messenger Marketing & Abandoned Cart App", app_store_url: "https://apps.shopify.com/recart", website_url: "https://recart.com", script_pattern: "api.recart.com", category: "Sales" }, { name: "Consistent Cart", short_description: "Messenger Marketing & Abandoned Cart Recovery", app_store_url: "https://apps.shopify.com/consistent-cart", website_url: "https://www.consistentcart.com/", script_pattern: "consistent_cart_addon.min.js", category: "Sales" }, { name: "Conversion+", short_description: "Free cart reservation countdown timer that increases sales", app_store_url: "https://apps.shopify.com/conversion", website_url: "https://trust.varinode.com/", script_pattern: "cv_initjs.php", category: "Sales" }, { name: "Stamped.io", short_description: "Collect Product reviews, site reviews and photo/video reviews", app_store_url: "https://apps.shopify.com/product-reviews-addon", website_url: "https://stamped.io", script_pattern: "stamped-io", category: "Sales" }, { name: "Shopify Product Reviews", short_description: "Default free shopify reviews app.", app_store_url: "https://apps.shopify.com/product-reviews", website_url: "https://help.shopify.com/en/manual/apps/apps-by-shopify/product-reviews", script_pattern: "productreviews.shopifycdn.com", category: "Sales" }, { name: "Varinode", short_description: "Free Ad exchange to help you acquire high quality traffic", app_store_url: "https://apps.shopify.com/ads", website_url: "http://avs.varinode.com", script_pattern: "avjs.php", category: "Sales" }, { name: "Loox", short_description: "Photo Reviews (Product Reviews)", app_store_url: "https://apps.shopify.com/loox", website_url: "https://loox.app", script_pattern: "loox.io/widget", category: "Sales" }, { name: "Firepush", short_description: "Order recovery with SMS and FREE Web push notifications", app_store_url: "https://apps.shopify.com/firepush", website_url: "https://firepush.io/", script_pattern: "firepush.", category: "Sales" }, { name: "Frequently Bought Together", short_description: "Amazon-like Bundle Recommendations, Upsell and Discounts", app_store_url: "https://apps.shopify.com/frequently-bought-together", website_url: "https://www.codeblackbelt.com", script_pattern: "js/modules/frequently-bought-together/main.min.js", category: "Sales" }, { name: "Shophero", short_description: "Email Marketing & Push Notification", app_store_url: "https://apps.shopify.com/shophero", website_url: "https://shophero.io/", script_pattern: "shophero.", category: "Marketing" }, { name: "LimeSpot", short_description: "Upsell, Cross-sell and Personalized Recommendations by AI", app_store_url: "https://apps.shopify.com/limespot", website_url: "https://www.limespot.com", script_pattern: "storefront/2.0.0/js/shopify/checkout-tracker.min.js", category: "Sales" }, { name: "McAfee SECURE", short_description: "Show visitors your site is secure", app_store_url: "https://apps.shopify.com/mcafee-secure", website_url: "https://www.mcafeesecure.com/for-consumers", script_pattern: "ywxi.net", category: "Trust and security" }, { name: "Quick View", short_description: "Product preview in a click", app_store_url: "https://apps.shopify.com/quick-view", website_url: "https://www.secomapp.com", script_pattern: "sca-qv-scripts-noconfig.js", category: "Sales" }, { name: "Judge.me", short_description: "Product Reviews", app_store_url: "https://apps.shopify.com/judgeme", website_url: "https://judge.me/", script_pattern: "cdn.judge.me/assets/installed.js", category: "Sales" }, { name: "Recharge", short_description: "Launch and scale your subscription and recurring business", app_store_url: "https://apps.shopify.com/subscription-payments", website_url: "https://rechargepayments.com", script_pattern: "static/js/recharge.js", category: "Sales" }, { name: "Code Black Belt Also Bought", short_description: "Recommendations - Customers Who Bought This Item Also Bought", app_store_url: "https://apps.shopify.com/also-bought", website_url: "https://www.codeblackbelt.com", script_pattern: "js/modules/also-bought/main.min.js", category: "Sales" }, { name: "Persistent Cart", short_description: "Remember customers' carts across their devices", app_store_url: "https://apps.shopify.com/remember-my-cart", website_url: "https://recovermycart.freshdesk.com/support/solutions/articles/33000213763-remember-my-cart-faq", script_pattern: "RememberMyCart/Manage/CartJS", category: "Sales" }, { name: "Wishy", short_description: "A beautiful, advanced & customizable wishlist plugin", app_store_url: "https://apps.shopify.com/wishy", website_url: "", script_pattern: "wishy-placer.production.min.js", category: "Sales" }, { name: "Bold Subscription", short_description: "Subscription Box and Recurring Orders", app_store_url: "https://apps.shopify.com/recurring-orders", website_url: "https://boldcommerce.com/bold-subscriptions", script_pattern: "v2_ui/js/ro.js", category: "Sales" }, { name: "Bold Upsell", short_description: "Product Upsell, Cross-sell & Smart Upsells to make more money", app_store_url: "https://apps.shopify.com/product-upsell", website_url: "https://boldcommerce.com", script_pattern: "v2_ui/js/upsell.js", category: "Sales" }, { name: "Yotpo", short_description: "Collect product reviews, site reviews, and photo reviews", app_store_url: "https://apps.shopify.com/yotpo-social-reviews", website_url: "https://www.yotpo.com", script_pattern: "staticw2.yotpo.com", category: "Sales" }, { name: "Bizzy", short_description: "Create urgency with recent sales notifications", app_store_url: "https://apps.shopify.com/bizzy-social-proof", website_url: "https://www.pixelunion.net/", script_pattern: "pxu-recent-sales-apps.s3.amazonaws.com/recent-sales", category: "Sales" }, { name: "MPS Buy Me", short_description: "Sticky Buy Button", app_store_url: "https://apps.shopify.com/mps-buy-me", website_url: "https://makeprosimp.com/", script_pattern: "buy-me-cdn.makeprosimp.com", category: "Sales" }, { name: "Product Options", short_description: "Product options to one or one thousand products with a click!", app_store_url: "https://apps.shopify.com/product-options", website_url: "https://nexusmedia-ua.com", script_pattern: "js/options.js", category: "Sales" }, { name: "Express Reviews", short_description: "Import reviews from AliExpress INSTANTLY", app_store_url: "https://apps.shopify.com/express-reviews", website_url: "https://appiversal.net/", script_pattern: "src/er.js", category: "Sales" }, { name: "East Side Co Cart Convert", short_description: "Product Upsell & Cross-sell", app_store_url: "https://apps.shopify.com/cart-convert", website_url: "https://eastsideco.com/", script_pattern: ".cartconvert.eastsideapps.io", category: "Sales" }, { name: "SMAR7", short_description: "Smart, adaptive & user friendly upsells", app_store_url: "https://apps.shopify.com/smar7-bundle-upsell", website_url: "https://smar7apps.com", script_pattern: "js/bundle-upsell.min.js", category: "Sales" }, { name: "Supr-i-t Aban. Cart Rem.", short_description: "Bring Back Your Store Visitors with Abandoned Cart Reminds", app_store_url: "https://apps.shopify.com/abandoned-cart-reminder", website_url: "https://spur-i-t.com", script_pattern: "shopify-apps/abandoned-cart-reminder/js/common.js", category: "Sales" }, { name: "Gift Wizard", short_description: "Gift Card Solutions, Loyalty and Rewards, Store Credit", app_store_url: "https://apps.shopify.com/giftwizard", website_url: "https://www.giftwizard.co/", script_pattern: "storefront.giftwizard.co/gift.js", category: "Sales" }, { name: "Csell", short_description: "Hand-picked product recommendations", app_store_url: "https://apps.shopify.com/cross-sell", website_url: "https://csell.co", script_pattern: "assets/v2/js/core/xsell.js", category: "Sales" }, { name: "Enorm Photo Reviews", short_description: "Review app for product reviews , photo reviews & site reviews", app_store_url: "https://apps.shopify.com/product-photo-reviews-by-enormapps", website_url: "https://www.enormapps.com", script_pattern: "productreviews/collection-embed.js", category: "Sales" }, { name: "In Cart Upsell", short_description: "Laser targeted upsell offers in the shopping cart - no popups!", app_store_url: "https://apps.shopify.com/in-cart-upsell", website_url: "http://www.incartupsell.com", script_pattern: "incartupsell.com", category: "Sales" }, { name: "Spur-i-t Social Proof", short_description: "Increase Sales & Create Urgency With SpurIT Social Proof App", app_store_url: "https://apps.shopify.com/social-proof-urgency", website_url: "https://spur-i-t.com", script_pattern: "shopify-extensions/social-proof/store/c54a5ad7c7b4a0069ca3eddae2a0406a.js", category: "Sales" }, { name: "Recovermycart", short_description: "Prevent abandoned orders", app_store_url: "https://apps.shopify.com/recover-my-cart", website_url: "https://recovermycart.squarespace.com", script_pattern: "Manage/CartJS_v2", category: "Sales" }, { name: "MinMaxify Order Limits", short_description: "Minimum - Maximum limits on your products, groups or entire cart", app_store_url: "https://apps.shopify.com/order-limits-minmaxify", website_url: "http://www.minmaxify.com/", script_pattern: "shopifyorderlimits.s3.amazonaws.com/limits", category: "Sales" }, { name: "Zotabox Social Sharing", short_description: "Social Share and Messaging Buttons. Improve Your Communication", app_store_url: "https://apps.shopify.com/social-buttons", website_url: "https://info.zotabox.com", script_pattern: "a384d78e2f3e7d78c9d09a15f7f1b51e/widgets.js", category: "Social media" }, { name: "Cartback", short_description: "Facebook Messenger Abandoned Cart app and Messenger Marketing", app_store_url: "https://apps.shopify.com/fb-messenger-remarketing", website_url: "", script_pattern: "messenger/js/exit_messenger.js", category: "Social media" }, { name: "Apps2grow.us Shop Instagram", short_description: "Stunning Instagram galleries that sell", app_store_url: "https://apps.shopify.com/instagram-photos", website_url: "http://www.apps2grow.us/instaphotos", script_pattern: "files/1/0016/7591/9458/t/1/assets/ssw-libraries.js", category: "Social media" }, { name: "Expertvillagemedia.com Instagram Feed & Gallery", short_description: "Top Instagram Gallery, Instagram Lookbook & Instagram Feed App", app_store_url: "https://apps.shopify.com/instagram-feed", website_url: "https://www.expertvillagemedia.com/shopify-apps/instafeed/", script_pattern: "expertvillagemedia.com/instagramfeed/embed.js", category: "Social media" }, { name: "Covet.pics", short_description: "Lookbook, Instagram & Customer Galleries", app_store_url: "https://apps.shopify.com/covet-pics", website_url: "https://covet.pics", script_pattern: "embed_v1.js", category: "Social media" }, { name: "Shopwave Reviews Wishlist", short_description: "Photos Reviews, Wishlist, Instagram, Loyalty and 7 apps in one", app_store_url: "https://apps.shopify.com/socialshopwave", website_url: "https://www.socialshopwave.com/", script_pattern: "scripts/socialshopwave", category: "Social media" }, { name: "Oxi Social Login", short_description: "One click login with Facebook, Google and many more", app_store_url: "https://apps.shopify.com/oxi-social-login", website_url: "http://www.oxiapps.com", script_pattern: "social-login.oxiapps.com/api/init", category: "Social media" }, { name: "Kudobuzz", short_description: "Testimonials and Reviews - Grow your business with social reviews", app_store_url: "https://apps.shopify.com/kudobuzz-testimonials", website_url: "https://kudobuzz.com/", script_pattern: "kudobuzz.com/widget", category: "Social media" }, { name: "AddThis Share Buttons", short_description: "Grow your website with free tools trusted by over 15M sites", app_store_url: "https://apps.shopify.com/addthis-sharing-tool", website_url: "https://www.addthis.com", script_pattern: "addthis_widget.js", category: "Social media" }, { name: "InstaShow or Yottie", short_description: "Instagram Feed or Embed any YouTube video and shaping video gallery", app_store_url: "https://apps.shopify.com/instashow", website_url: "https://elfsight.com", script_pattern: "shy.elfsight.com/p/platform.js", category: "Social media" }, { name: "Foursixty.com Shoppable Instagram", short_description: "Shop Instagram. Shoppable UGC. Rights Management. Anywhere.", app_store_url: "https://apps.shopify.com/foursixty", website_url: "http://www.foursixty.com", script_pattern: "media/scripts/fs.embed.v2.5.js", category: "Social media" }, { name: "Dvcloudsoftware Instagram", short_description: "Shop your instagram! Create an Instagram shop in minutes", app_store_url: "https://apps.shopify.com/instagram-in-shop", website_url: "http://instagram-shop.devcloudsoftware.com/support", script_pattern: "resource/resource.js", category: "Social media" }, { name: "Powr.io (Multiple possibilites)", short_description: "Social Media Feed or icons", app_store_url: "https://apps.shopify.com/partners/powr-io", website_url: "https://www.powr.io", script_pattern: "powr.js", category: "Social media" }, { name: "99Commerce Instagram Feed", short_description: "Instagram App to Add Instagram Gallery from Instagram Account", app_store_url: "https://apps.shopify.com/snapzy-the-instagram-feed", website_url: "http://www.99ecommerceexperts.com", script_pattern: "instagramfeedexperts.herokuapp.com/embed.js", category: "Social media" }, { name: "Zotabox Social Mobile Share Bar", short_description: "Free Mobile Messaging via WhatsApp, Messenger, Skype. SMS etc", app_store_url: "https://apps.shopify.com/mobile-messaging-social-share-bar", website_url: "https://info.zotabox.com/", script_pattern: "a384d78e2f3e7d78c9d09a15f7f1b51e/widgets.js", category: "Social media" }, { name: "Widgetic", short_description: "Facebook Like", app_store_url: "https://apps.shopify.com/facebook-like-by-widgetic", website_url: "https://widgetic.com", script_pattern: "sdk/sdk.js", category: "Social media" }, { name: "AAAE Instagram Shop", short_description: "Shoppable Instagram, Instagram Feed & Instagram Look Book APP", app_store_url: "https://apps.shopify.com/insta-feed", website_url: "https://www.aaaecommerce.com", script_pattern: "aaa-insta-feed-script.js", category: "Social media" }, { name: "Leadslide Social Media Tabs", short_description: "Design a Social Media Tab", app_store_url: "https://apps.shopify.com/social-media-tabs", website_url: "https://leadslide.com", script_pattern: "apps/leadslide-js", category: "Social media" }, { name: "Okas Open SignIn", short_description: "Social Login - Use any Social Network platform to login to your store", app_store_url: "https://apps.shopify.com/open-signin", website_url: "", script_pattern: "open-signin.okasconcepts.com", category: "Social media" }, { name: "Zestard Twitter Feed", short_description: "Responsive Widget to display tweets, follow button", app_store_url: "https://apps.shopify.com/twitter-feed", website_url: "https://www.zestard.com", script_pattern: "zestard_tweet_feed.js", category: "Social media" }, { name: "Autoketing Facebook Chat", short_description: "Live chat with customers via Facebook Messenger", app_store_url: "https://apps.shopify.com/facebook-chat-box", website_url: "https://autoketing.com", script_pattern: "dist/fb-chat-embed.js", category: "Social media" }, { name: "Likebtn.com", short_description: "Get tons of likes and boost sharing", app_store_url: "https://apps.shopify.com/like-button-rating", website_url: "https://likebtn.com", script_pattern: "w.likebtn.com/js/w/widget.js", category: "Social media" }, { name: "Sketch ThemesInstagram Feed", short_description: "Add aliveness to your store by integrating Instagram's feeds", app_store_url: "https://apps.shopify.com/instagram-feed-by-sketch-themes", website_url: "", script_pattern: "live/instagram_feeds/js/instaapp_loadn.js", category: "Social media" }, { name: "Sprbot Instagram Shop Feed", short_description: "Make your Instagram Feed Shop-able", app_store_url: "https://apps.shopify.com/dev-instagram-sell-1", website_url: "http://sprbot.com/instashop/", script_pattern: "instagram-sell/ins-shop.js", category: "Social media" }, { name: "TagTray", short_description: "Shop Galleries Of Customer Generated Social Media Photos", app_store_url: "https://apps.shopify.com/tagtray", website_url: "https://www.tagtray.com/", script_pattern: "v3/tagtray.js", category: "Social media" }, { name: "CFF Shareable Cart", short_description: "Makes your cart shareable and transferrable between devices", app_store_url: "https://apps.shopify.com/portable-cart", website_url: "https://customerfirstfocus.com/", script_pattern: "cff.production.min.js", category: "Social media" }, { name: "Roar Social Caller", short_description: "Social Caller gives you a hand, to increase your inbound calls", app_store_url: "https://apps.shopify.com/social-caller", website_url: "https://roartheme.com/", script_pattern: "socialcaller/lib/assets/socialcaller.js", category: "Social media" }, { name: "Swym.it Wishlist Plus", short_description: "Help your customers pick up where they left off", app_store_url: "https://apps.shopify.com/swym-relay", website_url: "http://swym.it", script_pattern: "code/swym-shopify.js", category: "Customer service" }, { name: "Tidiochat", short_description: "Live chat boosted with Bots and Marketing Automation", app_store_url: "https://apps.shopify.com/tidio-chat", website_url: "http://www.tidiochat.com", script_pattern: "tidiochat.com", category: "Customer service" }, { name: "Chilli Abandonment Protector", short_description: "Email marketing automation & Popups with Exit intent", app_store_url: "https://apps.shopify.com/linkerfriend-lead-management-tools", website_url: "https://www.chilliapps.com", script_pattern: "main/chpmgr.js", category: "Customer service" }, { name: "AWIO", short_description: "Contact Us Page Generator and Popup Contact Widget", app_store_url: "https://apps.shopify.com/improved-contact-form", website_url: "https://www.awio.com", script_pattern: "improvedcontactform.com/icf.js", category: "Customer service" }, { name: "WhatsHelp.io", short_description: "Chat with website visitors via popular Messaging Apps", app_store_url: "https://apps.shopify.com/whatshelp-chat-button", website_url: "https://whatshelp.io/widget", script_pattern: "whatshelp.io/shopify/widget", category: "Customer service" }, { name: "Facebook Live Chat1", short_description: "Customer Support via Facebook Live Chat", app_store_url: "https://apps.shopify.com/facebook-messenger-live-chat", website_url: "https://info.zotabox.com", script_pattern: "sdk/xfbml.customerchat.js#xfbml=1&version=v2.11", category: "Customer service" }, { name: "Chatra", short_description: "Live chat and Facebook chat for your store", app_store_url: "https://apps.shopify.com/chatra", website_url: "https://chatra.io", script_pattern: "shopify?chatraId", category: "Customer service" }, { name: "Hulk Contact Us Form", short_description: "Take Less Than 2 Minutes to Get In Touch With Your Customers", app_store_url: "https://apps.shopify.com/contact-us-by-hulkapps", website_url: "https://www.hulkcode.com", script_pattern: "skeletopapp.js", category: "Customer service" }, { name: "AAAE Form Builder", short_description: "Form Builder App with Custom Registration Form and Order Form", app_store_url: "https://apps.shopify.com/form-builder", website_url: "https://www.aaaecommerce.com/", script_pattern: "formbuilder.aaawebstore.com/appfiles/aaa_form_builder_script_minify.js", category: "Customer service" }, { name: "Zendesk Support", short_description: "Omnichannel customer service and engagement platform", app_store_url: "https://apps.shopify.com/zendesk", website_url: "https://www.zendesk.com", script_pattern: "zendesk-embeddable.js", category: "Customer service" }, { name: "Re:amaze", short_description: "Customer support helpdesk with live chat, ticketing, and FAQ", app_store_url: "https://apps.shopify.com/reamaze", website_url: "https://www.reamaze.com", script_pattern: "reamaze.com", category: "Customer service" }, { name: "Orderify", short_description: "Let customers edit, cancel and reorder instantly", app_store_url: "https://apps.shopify.com/orderify", website_url: "https://customerfirstfocus.com", script_pattern: "cffOrderEdit.production.min.js", category: "Customer service" }, { name: "Etoile Ultimate FAQ", short_description: "A feature-rich and complete FAQ solution", app_store_url: "https://apps.shopify.com/ultimate-faqs", website_url: "https://www.etoilewebdesign.com", script_pattern: "ewd-ufaq-js.js", category: "Customer service" }, { name: "Zendesk Chat", short_description: "Live chat provides a fast way to connect with customers", app_store_url: "https://apps.shopify.com/zendeskchatplus", website_url: "http://help.combidesk.com/instruction-manuals/shopify/instruction-manual-shopify-zendesk-chat-integration-formerly-zopim", script_pattern: "js/integration/shopify/zopim/widget.js", category: "Customer service" }, { name: "Facebook Chat", short_description: "Turn your visitors into your customers with Facebook Messenger", app_store_url: "https://apps.shopify.com/facebook-chat-2-0", website_url: "", script_pattern: "chat/loader", category: "Customer service" }, { name: "Pure Chat", short_description: "Easy-to-use live chat software with unlimited users and chats", app_store_url: "https://apps.shopify.com/pure-chat", website_url: "https://www.purechat.com/", script_pattern: "purechat.com", category: "Customer service" }, { name: "Jivo Omnichannel Suite", short_description: "Finally! Chats, FB messages, calls & emails, all in one app", app_store_url: "https://apps.shopify.com/jivochat", website_url: "https://www.jivochat.com/", script_pattern: "jivosite.com/script/widget", category: "Customer service" }, { name: "Custom Order Status", short_description: "Create and manage the status of your orders", app_store_url: "https://apps.shopify.com/ultimate-order-status", website_url: "http://www.w3trends.com", script_pattern: "js/orderlookup.js", category: "Customer service" }, { name: "Mageworx Product Fees", short_description: "Add extra fees to incease your sales and average order value", app_store_url: "https://apps.shopify.com/product-fees", website_url: "https://appstore.mageworx.com/", script_pattern: "productfees/source.js", category: "Customer service" }, { name: "Google Reviews", short_description: "Add Google Customer Reviews to your site, no coding required!", app_store_url: "https://apps.shopify.com/easy-google-customer-reviews", website_url: "https://unionworks.co.uk/shopify-apps/easy-google-customer-reviews/support", script_pattern: "scripts/google-customer-reviews-badge.js", category: "Customer service" }, { name: "Free Call", short_description: "Service for Direct Sales", app_store_url: "https://apps.shopify.com/free-call", website_url: "https://www.freecallinc.com", script_pattern: "freecall_trackdiv1.js", category: "Customer service" }, { name: "Two Zillas Tracking Genie", short_description: "Tracking set on autopilot", app_store_url: "https://apps.shopify.com/trackinggenie", website_url: "http://www.twozillas.com", script_pattern: "trackinggenie.co", category: "Customer service" }, { name: "Facebook Live Chat", short_description: "Chat with your shoppers via Facebook Messenger", app_store_url: "https://apps.shopify.com/facebook-messenger-live-chat-tracking", website_url: "https://roartheme.com", script_pattern: "fblivechat/lib/asset/script.js", category: "Customer service" }, { name: "Spice Gems Returns", short_description: "Handle Return Requests & send Prepaid Shipping Labels", app_store_url: "https://apps.shopify.com/return-management-system", website_url: "https://spicegems.com", script_pattern: "assets/embedOrderLookup.js", category: "Customer service" }, { name: "Raven Callback Request", short_description: "Turn website visitors into qualified sales calls", app_store_url: "https://apps.shopify.com/raven", website_url: "http://raven-callback.webflow.io", script_pattern: "raven-script/pipoldidik/raven-widget.js", category: "Customer service" }, { name: "Formilla Live Chat", short_description: "Live chat with visitors in real-time", app_store_url: "https://apps.shopify.com/formilla-live-chat", website_url: "https://www.formilla.com", script_pattern: "loadFormilla.js", category: "Customer service" }, { name: "Powerful Form Builder", short_description: "Create any kind of custom form with Powerful Form Builder app", app_store_url: "https://apps.shopify.com/powerful-form-builder", website_url: "http://www.globosoftware.net", script_pattern: "s/files/1/0016/7591/9458/t/1/assets/globoformbuilder_init.js", category: "Customer service" }, { name: "Delivery Date Range", short_description: "Display the estimated delivery date range on the product page", app_store_url: "https://apps.shopify.com/delivery-date-range", website_url: "http://www.ecomstoreapps.com", script_pattern: "ddr_embed.js", category: "Customer service" }, { name: "EastSideCo Forms", short_description: "Smart Contact Form Builder", app_store_url: "https://apps.shopify.com/contact-forms-1", website_url: "https://eastsideco.com", script_pattern: "widget/2.10.2/uploadcare/uploadcare.full.min.js", category: "Customer service" }, { name: "Wholesale Simplified", short_description: "Merchants can offer discounts to different customer groups", app_store_url: "https://apps.shopify.com/wholesale-simplified", website_url: "http://support.solvercircle.com", script_pattern: "wholesale-simplified/scripts", category: "Customer service" }, { name: "Develic Maps", short_description: "Add Google Maps with store locations to your Shopify store", app_store_url: "https://apps.shopify.com/maps-by-develic", website_url: "https://www.develic.com/", script_pattern: "maps.develic.com", category: "Customer service" }, { name: "Estimated Delivery Date", short_description: "Displays the estimated delivery date on the product page", app_store_url: "https://apps.shopify.com/estimated-delivery-date", website_url: "http://www.estimateddelivery.com", script_pattern: "assets/js/countdown/moment.js", category: "Customer service" }, { name: "Easy GDPR", short_description: "Get GDPR compliant with 1 click. Cookie bar", app_store_url: "https://apps.shopify.com/easy-gdpr", website_url: "https://www.easygdpr.io", script_pattern: "gdpr.min.js", category: "Customer service" }, { name: "Smart Search", short_description: "Smart Search, Filters, Recommendations to boost conversion.", app_store_url: "https://apps.shopify.com/searchanise", website_url: "https://start.searchanise.com/shopify", script_pattern: "searchanise.com/widgets/shopify/init.js", category: "Sales" }, { name: "Hubspot", short_description: "Integrate marketing, sales, online data and more!", app_store_url: "https://apps.shopify.com/hubspot", website_url: "https://hubspot.com", script_pattern: "api.hubapi.com", category: "Marketing" }, { name: "Exto", short_description: "Upsell and cross-sell recommendations", app_store_url: "https://apps.shopify.com/automatic-related-products", website_url: "http://shopify.exto.io/", script_pattern: "apps1.exto.io", category: "Sales" }, { name: "Back in Stock", short_description: "Back in Stock Notification alerts", app_store_url: "https://apps.shopify.com/back-in-stock", website_url: "https://backinstock.org", script_pattern: "app.backinstock.org", category: "Sales" }, { name: "SLoyalty", short_description: "Reward customers, build loyalty and grow referral sales.", app_store_url: "https://apps.shopify.com/s-loyalty", website_url: "https://www.sloyalty.com/", script_pattern: "sloyalty.shopify.js", category: "Marketing" }, { name: "Trackify", short_description: "Pixel App and Facebook Audience Builder", long_description: "All-in-one Facebook pixel app that lets you integrate multiple pixels, add advanced event data, and see your ROI take off.", app_store_url: "https://apps.shopify.com/trackify-1", website_url: "http://help.redretarget.com/trackify", script_pattern: "trackify_script.js", category: "Marketing" }, { name: "Adroll", short_description: "Retargeting", app_store_url: "https://apps.shopify.com/adroll-retargeting", website_url: "http://www.adroll.com", script_pattern: ".adroll.com", category: "Advertising" }, { name: "Carts Guru", short_description: "Shopping cart abandonment", app_store_url: "https://apps.shopify.com/cartsguru", website_url: "http://carts.guru", script_pattern: "carts.guru", category: "Sales" }, { name: "East Side Co - Back In Stock", short_description: "Email and SMS Out of Stock alerts", app_store_url: "https://apps.shopify.com/out-of-stock-1", website_url: "https://eastsideco.com/shopify-apps", script_pattern: "intlTelInput.js", category: "Sales" }, { name: "Lead Dyno", short_description: "Affiliate and influencer marketing", app_store_url: "https://apps.shopify.com/leaddyno", website_url: "http://leaddyno.com", script_pattern: "leaddyno.com", category: "Affiliate" }, { name: "Signifyd", short_description: "Guaranteed fraud and chargeback protection", app_store_url: "https://apps.shopify.com/signifyd", website_url: "https://www.signifyd.com", script_pattern: "cdn-scripts.signifyd.com", category: "Sales" }, { name: "ShopMessage", short_description: "FB Messenger", app_store_url: "https://apps.shopify.com/shopmessage", website_url: "https://www.shopmessage.me", script_pattern: "shopmessage_platform.js", category: "Marketing" }, { name: "Smart Wishlist", short_description: "Wishlist", app_store_url: "https://apps.shopify.com/smart-wishlist", website_url: "https://www.webmarked.net", script_pattern: "smartwishlist.js", category: "Marketing" }, { name: "Hypervisual", short_description: "Beautiful landing and product pages", app_store_url: "https://apps.shopify.com/hypervisual", website_url: "https://gethypervisual.com", script_pattern: "hypervisual.js", category: "Store Design" }, { name: "Fomo", short_description: "Increase Conversions with Social Proof Automation", app_store_url: "https://apps.shopify.com/fomo", website_url: "https://fomo.com/", script_pattern: "load.fomo.com", category: "Sales" }, { name: "Currency Converter", short_description: "Show prices in customers local currency", app_store_url: "https://apps.shopify.com/doubly-currency-converter", website_url: "", script_pattern: "doubly.js", category: "Store Design" }, { name: "Klaviyo", short_description: "Email and social campaigns", app_store_url: "https://apps.shopify.com/klaviyo-email-marketing", website_url: "https://www.klaviyo.com/", script_pattern: "klaviyo.js", category: "Marketing" }, { name: "Credible", short_description: "Sales Booster", app_store_url: "https://apps.shopify.com/credible", website_url: "http://convertwithcredible.com", script_pattern: "credible.js", category: "Sales" }, { name: "Hektor Commerce - Discount Direct", short_description: "Automatically apply discounts through a custom URL", app_store_url: "https://apps.shopify.com/discount-direct", website_url: "", script_pattern: "discountdirect.js", category: "Marketing" }, { name: "Affiliatly", short_description: "Affiliate tracking", app_store_url: "https://apps.shopify.com/affiliatly", website_url: "https://www.affiliatly.com", script_pattern: "affiliatly.com", category: "Affiliate" }, { name: "Product Filter", short_description: "Product filter & search", app_store_url: "https://apps.shopify.com/product-filter-search", website_url: "https://boostcommerce.net", script_pattern: "bc-sf-filter.js", category: "Store Design" }, { name: "Hive", short_description: "Send targeted email campaigns", app_store_url: "https://apps.shopify.com/hive", website_url: "https://www.hive.co", script_pattern: "cdn-prod.hive.co", category: "Marketing" }, { name: "Nosto", short_description: "Powerful Personalization", app_store_url: "https://apps.shopify.com/nosto-personalization-for-shopify", website_url: "http://nosto.com", script_pattern: "connect.nosto.com", category: "Sales" }, { name: "Coin", short_description: "Automatic currency conversion", app_store_url: "https://apps.shopify.com/coin", website_url: "https://www.theshoppad.com/coin-for-shopify", script_pattern: "coin.js", category: "Store Design" }, { name: "Riskified", short_description: "Fraud prevention", app_store_url: "https://www.riskified.com", website_url: "https://www.riskified.com", script_pattern: "beacon.riskified.com", category: "Marketing" }, { name: "Retention Rocket", short_description: "Retention Marketing", app_store_url: "https://retentionrocket.com/", website_url: "https://retentionrocket.com/", script_pattern: "cdn.retentionrock.com", category: "Marketing" }, { name: "Appifiny - Recently", short_description: "Recently purchased popup notifications", app_store_url: "https://apps.shopify.com/recently", website_url: "https://appifiny.co.uk", script_pattern: "recently.appifiny.io", category: "Sales" }, { name: "Octane - AI Messenger", short_description: "Facebook Messenger", app_store_url: "https://apps.shopify.com/octane-ai-messenger-marketing", website_url: "https://octaneai.com", script_pattern: "octaneai.com", category: "Sales" }, { name: "GeoIP", short_description: "Redirect Visitors based on their IP Address", app_store_url: "https://apps.shopify.com/geoip-country-redirect", website_url: "https://spicegems.com", script_pattern: "conditional-redirect.spicegems.com/js/scripttags", category: "Store Design" }, { name: "Lamify- Please Stay", short_description: "Recover Sales with Your Tab", app_store_url: "https://apps.shopify.com/please-stay", website_url: "https://www.pleasestay.co", script_pattern: "pleasestay.js", category: "Sales" }, { name: "Automatic Discount", short_description: "Apply automatic discounts", app_store_url: "https://apps.shopify.com/automatic-discount-rules", website_url: "https://desk.zoho.com/portal/tabarnapp/home", script_pattern: "wallsh_dp.min.js", category: "Marketing" }, { name: "Cart Notifications", short_description: "Stylish favicon notification to reduce cart abandonment", app_store_url: "https://apps.shopify.com/cart-notifications", website_url: "", script_pattern: "cart-notifications", category: "Store Design" }, { name: "SimplyTick", short_description: "Reporting", app_store_url: "https://apps.shopify.com/simplytick", website_url: "https://simplytick.com/", script_pattern: "simplytick.com", category: "Sales" }, { name: "Secomapp Free Gifts", short_description: "Free Gifts", app_store_url: "https://apps.shopify.com/freegifts", website_url: "https://secomapp.com/", script_pattern: "freegifts/app/freegifts", category: "Marketing" }, { name: "Bold Sales Motivator", short_description: "Increase the amount of every order", app_store_url: "https://apps.shopify.com/the-motivator", website_url: "http://boldcommerce.com/", script_pattern: "motivate.boldapps.net/motivator.php", category: "Sales" }, { name: "Product Labels", short_description: "Product Labels", app_store_url: "https://apps.shopify.com/product-labels", website_url: "https://secomapp.com", script_pattern: "cdn.secomapp.com/product_label", category: "Store Design" }, { name: "Order Deadline", short_description: "Order Deadline", app_store_url: "https://apps.shopify.com/order-deadline", website_url: "https://www.evilegg.co.uk", script_pattern: "order-deadline.min.js", category: "Sales" }, { name: "Dealio", short_description: "Gamified Up-Sell", app_store_url: "https://apps.shopify.com/dealio-gamified-product-page-up-sell-app", website_url: "http://www.dealio-app.com", script_pattern: "dealioapp.azurewebsites.net", category: "Sales" }, { name: "Bold - Custom Pricing", short_description: "Custom Pricing ‑ Wholesale", app_store_url: "https://apps.shopify.com/customer-pricing", website_url: "https://boldcommerce.com/custom-pricing", script_pattern: "customer_pricing.php", category: "Sales" }, { name: "Easy Messenger", short_description: "Live Chat", app_store_url: "https://apps.shopify.com/easymessenger-livechat-messenger-as-a-live-chat", website_url: "https://nexusmedia-ua.com", script_pattern: "easybot.js", category: "Customer service" }, { name: "Code Black Belt Currency Converter", short_description: "Currency Converter for Multi Currency Stores", app_store_url: "https://apps.shopify.com/currency-converter-plus", website_url: "https://www.codeblackbelt.com", script_pattern: "currency-converter-plus/main.min.js", category: "Store Design" }, { name: "TrustBadges", short_description: "Authenticate And Build Trust", app_store_url: "https://apps.shopify.com/trust-by-kamozi", website_url: "https://kamozi.io/trust", script_pattern: "kamozi_trusted.js", category: "Trust and security" }, { name: "Bold Quantity Break", short_description: "Quantity Breaks,Tiered Pricing and Bulk Discounts", app_store_url: "https://apps.shopify.com/quantity-breaks", website_url: "https://boldcommerce.com/quantity-breaks", script_pattern: "quantity_breaks.php", category: "Sales" }, { name: "Stock Counter", short_description: "Social Proof and Scarcity", app_store_url: "https://apps.shopify.com/pressure-cooker", website_url: "https://websiteondemand.ca", script_pattern: "pressure-cooker.js", category: "Sales" }, { name: "Recomify", short_description: "Related Products", app_store_url: "https://apps.shopify.com/recomify", website_url: "https://www.recomify.com", script_pattern: "app.recomify.com/script_tag.js", category: "Sales" }, { name: "Sales Pop", short_description: "Automatically show recent transaction", app_store_url: "https://apps.shopify.com/sales-pop-master", website_url: "https://autoketing.com", script_pattern: "sales-pop-dot-autoketing-production-sdk.appspot.com", category: "Sales" }, { name: "Sales Notification", short_description: "Recent sales", app_store_url: "https://apps.shopify.com/mps-sales-notification", website_url: "https://makeprosimp.com", script_pattern: "sales-notification.makeprosimp.com", category: "Sales" }, { name: "Trust Badge", short_description: "Beautiful payment badges", app_store_url: "https://apps.shopify.com/trust-badge", website_url: "", script_pattern: "hektorcommerce.com/apps/trustbadge", category: "Trust and security" }, { name: "Trust Hero", short_description: "More Trust, More Sales", app_store_url: "https://apps.shopify.com/trust-hero", website_url: "", script_pattern: "assets/trust_hero", category: "Trust and security" }, { name: "Full Page Zoom", short_description: "High quality full screen image zoom for high quality images", app_store_url: "https://apps.shopify.com/full-page-zoom", website_url: "https://www.codeblackbelt.com", script_pattern: "cdn.codeblackbelt.com/js/modules/full-page-zoom/main.min.js", category: "Store Design" }, { name: "Checkout Share", short_description: "Turn every conversion into a conversation", app_store_url: "https://apps.shopify.com/checkout-share", website_url: "https://spacesquirrel.co/checkout-share", script_pattern: "checkoutshare.spacesquirrel.net/embed_share_a_purchase.js", category: "Sales" }, { name: "ReCharge", short_description: "Subscriptions by ReCharge", app_store_url: "https://apps.shopify.com/subscription-payments", website_url: "https://rechargepayments.com", script_pattern: "rechargeassets-bootstrapheroes-rechargeapps.netdna-ssl.com", category: "Sales" }, { name: "Klarna", short_description: "Klarna Payments", app_store_url: "https://www.klarna.com/international/business/shopify", website_url: "https://www.klarna.com/international/business/shopify", script_pattern: "www.klarnapayments.com/assets/upstream.js", category: "Sales" }, { name: "Back in Stock Alerts", short_description: "Set Up Back in Stock Notifications for Out of Stock Products", app_store_url: "https://apps.shopify.com/in-stock-reminder", website_url: "https://spur-i-t.com", script_pattern: "in-stock-reminder/js/common.js", category: "Marketing" }, { name: "Analytics", short_description: "Data Management", app_store_url: "https://gator.io", website_url: "https://gator.io", script_pattern: "api.gator.io/v1/analytics", category: "Marketing" }, { name: "Recomatic Related Products", short_description: "Product recommendations", app_store_url: "https://apps.shopify.com/recomatic", website_url: "http://www.recomaticapp.com", script_pattern: "recomaticapp2-wordsensesas.netdna-ssl.com", category: "Sales" }, { name: "Pixel Union Countdown", short_description: "Countdown Sales Timer", app_store_url: "https://apps.shopify.com/countdown-timers", website_url: "https://www.pixelunion.net", script_pattern: "apps.pixelunion.net/scripts/js/countdown/bundle.min.js", category: "Sales" }, { name: "Loyalty Rewards", short_description: "Loyalty Rewards Referral Point", app_store_url: "https://apps.shopify.com/referral-loyalty", website_url: "https://www.aaaecommerce.com", script_pattern: "aaa-refferal-script.js", category: "Marketing" }, { name: "EggViews", short_description: "Product Reviews", app_store_url: "https://apps.shopify.com/eggviews", website_url: "https://www.gowebbaby.com", script_pattern: "eggViewsScript_v2.js", category: "Sales" }, { name: "Sales Booster", short_description: "Boost sales- BOGO and upsell", app_store_url: "https://apps.shopify.com/checkout-booster", website_url: "https://www.aaaecommerce.com/", script_pattern: "checkoutbooster_v1.js", category: "Sales" }, { name: "Kount", short_description: "Fraud Prevention and Detection", app_store_url: "https://kount.com", website_url: "https://kount.com", script_pattern: "shopify.kount.net", category: "Sales" }, { name: "Multi Vendor", short_description: "Convert your ECommerce Store", app_store_url: "https://apps.shopify.com/multi-vendor-marketplace", website_url: "https://webkul.com", script_pattern: "shopify.webkul.com/multivendor/js/download_prod.js", category: "Products" }, { name: "Pixlee", short_description: "UGC + Shoppable IG", app_store_url: "https://apps.shopify.com/pixlee", website_url: "https://www.pixlee.com", script_pattern: "pixlee.shopify.v2.prod.js", category: "Sales" }, { name: "Infinite Options", short_description: "Customize your products", app_store_url: "https://apps.shopify.com/custom-options", website_url: "https://www.theshoppad.com/infinite-options-for-shopify", script_pattern: "customizery.js", category: "Store Design" }, { name: "Variant Image Automator", short_description: "Show multiple images of variants", app_store_url: "https://apps.shopify.com/variant-image-automator", website_url: "", script_pattern: "variant-image-automator.starapps.studio/product_variants.js", category: "Store Design" }, { name: "Variant Descriptions", short_description: "Show Variant Specific Details", app_store_url: "https://apps.shopify.com/variant-descriptions-by-starapps", website_url: "", script_pattern: "variant-descriptions.starapps.studio/apps.js", category: "Store Design" }, { name: "Announcement Bar", short_description: "Promote discounts on an announcement bar", app_store_url: "https://apps.shopify.com/quick-announcement-bar-always-keep-your-customers-informed", website_url: "https://hextom.com", script_pattern: "quickannouncementbar.js", category: "Store Design" }, { name: "Ultimate Sales Boost", short_description: "Increase sales with scarcity, urgency, trust", app_store_url: "https://apps.shopify.com/ultimate-sales-boost", website_url: "https://hextom.com", script_pattern: "ultimatesalesboost.js", category: "Sales" }, { name: "Preorderly", short_description: "Pre orders", app_store_url: "https://apps.shopify.com/preorderly", website_url: "http://www.codeinero.net", script_pattern: "preorderly.azurewebsites.net/Scripts/preorder.min.js", category: "Orders" }, { name: "Messenger", short_description: "Sell products and provide customer support from Messenger", app_store_url: "https://apps.shopify.com/messenger", website_url: "", script_pattern: "messenger_commerce/assets/new_message_us", category: "Customer service" }, { name: "Shipping Rates Calculator", short_description: "Shipping rates calculator with geolocation", app_store_url: "https://apps.shopify.com/shipping-rates-calculator-plus", website_url: "https://www.codeblackbelt.com", script_pattern: "cdn.codeblackbelt.com/js/modules/shipping-rates-calculator-plus", category: "Orders" }, { name: "Shoelace", short_description: "Retargeting Journeys", app_store_url: "https://apps.shopify.com/shoelace-retargeting", website_url: "https://shoelace.com", script_pattern: "lace.shoelace.com", category: "Marketing" }, { name: "Quantity Discount", short_description: "Add Quantity Discount or Tiered Pricing", app_store_url: "https://apps.shopify.com/pricing-by-quantity", website_url: "https://spur-i-t.com", script_pattern: "pricing-by-quantity/js/clear-cart.js", category: "Sales" }, { name: "Sticky Add To Cart", short_description: "Dramatically enhance your ADD TO CART and CHECKOUT process", app_store_url: "https://apps.shopify.com/sticky-add-to-cart-bar", website_url: "http://www.codeinero.net", script_pattern: "stickyaddtocartbar.azurewebsites.net/Scripts/satcb.min.js", category: "Store Design" }, { name: "Product Accessories", short_description: "Show related Product Accessories directly on your product page", app_store_url: "https://apps.shopify.com/product-accessories", website_url: "http://www.w3trends.com", script_pattern: "accessories.js", category: "Sales" }, { name: "Tobi", short_description: "SMS + FREE Facebook Messenger", app_store_url: "https://apps.shopify.com/tobi", website_url: "https://tobi.ai", script_pattern: "tobi.ai", category: "Customer Service" }, { name: "Gift Reggie", short_description: "Gift Registry and Wishlist", app_store_url: "https://apps.shopify.com/gift-reggie-by-eshop-admin", website_url: "https://gift-reggie.eshopadmin.com", script_pattern: "gift-reggie.eshopadmin.com", category: "Sales" }, { name: "Bold Brain", short_description: "Product recomendations", app_store_url: "https://apps.shopify.com/the-bold-brain", website_url: "https://boldcommerce.com", script_pattern: "brain-assets.boldapps.net/js/analytics.js", category: "Sales" }, { name: "OptiMonk", short_description: "Exit intent popups", app_store_url: "https://apps.shopify.com/optimonk", website_url: "http://optimonk.com", script_pattern: "front.optimonk.com", category: "Marketing" }, { name: "No Fraud", short_description: "Prevent Fraud Chargebacks, Accept More Orders", app_store_url: "https://apps.shopify.com/nofraud-chargeback-prevention-and-protection", website_url: "https://www.nofraud.com", script_pattern: "services.nofraud.com/js/device.js", category: "Orders and shipping" }, { name: "Product Customizer", short_description: "Easily add options, variants & customization to your products", app_store_url: "https://apps.shopify.com/product-customizer", website_url: "http://productcustomizer.com", script_pattern: "shopify-product-customizer.js", category: "Store Design" }, { name: "Verge", short_description: "SEO JSON‑LD Boost", app_store_url: "https://apps.shopify.com/seo-json-ld-boost-by-verge", website_url: "https://vergegraphics.com", script_pattern: "verge-json-ld.js", category: "Marketing" }, { name: "Varinode Trust", short_description: "Trust seals and review tools", app_store_url: "https://apps.shopify.com/trust", website_url: "https://trust.varinode.com", script_pattern: "verify.varinode.com/ts_js.php", category: "Trust and security" }, { name: "Custom Product Options", short_description: "Product options", app_store_url: "https://apps.shopify.com/best-custom-product-options", website_url: "https://www.relentlessapps.com", script_pattern: "best_custom_product_options.js", category: "Store Design" }, { name: "Globo", short_description: "Straight to Checkout", app_store_url: "https://apps.shopify.com/straight-to-checkout-skip-cart", website_url: "http://globosoftware.net", script_pattern: "globocheckout_init.js", category: "Store Design" }, { name: "Skip Cart", short_description: "Faster Checkouts to Reduce Abandoned Carts", app_store_url: "https://apps.shopify.com/skip-cart-the-fast-way-to-checkout", website_url: "", script_pattern: "skipcart.js", category: "Store Design" }, { name: "Metrilo", short_description: "Marketing Platform", app_store_url: "https://apps.shopify.com/metrilo", website_url: "https://www.metrilo.com", script_pattern: "shoparty.metrilo.com", category: "Marketing" }, { name: "W3 - Store Locator", short_description: "Easily add locations to a map for your customers to find you", app_store_url: "https://apps.shopify.com/store-locator-w3", website_url: "http://www.w3trends.com", script_pattern: "storelocator.w3apps.co/js/include.js", category: "Store Design" }, { name: "Marsello - Loyalty", short_description: "Sell more with a loyalty program and automated email marketing", app_store_url: "https://apps.shopify.com/marsello", website_url: "https://www.marsello.com", script_pattern: "app.marsello.com", category: "Marketing" }, { name: "Uploadery", short_description: "Give your customers the ability to send files with their order", app_store_url: "https://apps.shopify.com/uploadery", website_url: "https://www.theshoppad.com/uploadery-for-shopify", script_pattern: "uploadery.js", category: "Store Design" }, { name: "Cooki", short_description: "Easy GDPR compliance", app_store_url: "https://apps.shopify.com/cooki", website_url: "https://www.theshoppad.com/uploadery-for-shopify", script_pattern: "cookihq.com", category: "Trust and Security" }, { name: "Giftship", short_description: "Ship to Multiple Addresses, Gift Messages", app_store_url: "https://apps.shopify.com/giftship", website_url: "https://appsbypix.com/", script_pattern: "giftship.4.2.10.js", category: "Sales" }, { name: "EasyVideo", short_description: "Easily add product videos", app_store_url: "https://apps.shopify.com/easyvideo", website_url: "https://nexusmedia-ua.com/pages/contact", script_pattern: "easyvideo_v2.js", category: "Store Design" }, { name: "Pixel Perfect", short_description: "Product Feeds and Audiences made Simple", app_store_url: "https://apps.shopify.com/pixel-perfect", website_url: "https://www.wyred-up.com", script_pattern: "pixel-perfect.js", category: "Marketing" }, { name: "Teelaunch", short_description: "Print on Demand", app_store_url: "https://apps.shopify.com/teelaunch-1", website_url: "https://teelaunch.com", script_pattern: "teelaunch-scripts.js", category: "Products" }, { name: "Timer Plus", short_description: "Countdown", app_store_url: "https://apps.shopify.com/timer-plus", website_url: "", script_pattern: "timerplus/files/js/timer.js", category: "Sales" }, { name: "JetPrint Fulfillment", short_description: "Print-On-Demand Fulfillment", app_store_url: "https://apps.shopify.com/jetprint-fulfillment", website_url: "https://www.jetprintapp.com", script_pattern: "customization.jetprintapp.com", category: "Store Design" }, { name: "Uplinkly", short_description: "Sticky Cart", app_store_url: "https://apps.shopify.com/sticky-cart-by-uplinkly", website_url: "https://www.uplinkly.com", script_pattern: "sticky-cart.uplinkly-static.com", category: "Store Design" }, { name: "Smart Push Marketing", short_description: "Web push notifications", app_store_url: "https://apps.shopify.com/web-push-notification", website_url: "https://hextom.com", script_pattern: "smartpushmarketing.js", category: "Marketing" }, { name: "Yeps", short_description: "Shipping & announcement bar", app_store_url: "https://apps.shopify.com/yeps-io", website_url: "https://yeps.io", script_pattern: "app.yeps.io", category: "Store Design" }, { name: "Nfcube", short_description: "Instagram Feed", app_store_url: "https://apps.shopify.com/instafeed", website_url: "https://shopify.nfcube.com", script_pattern: "instafeed.nfcube.com", category: "Marketing" }, { name: "ID Discount", short_description: "Military Discount", app_store_url: "https://apps.shopify.com/military-discount", website_url: "https://id.discount", script_pattern: "cdn.id.discount/seller/launcher.js", category: "Marketing" }, { name: "Sky Pilot", short_description: "Seamless File and Video Delivery", app_store_url: "https://apps.shopify.com/sky-pilot", website_url: "https://www.skypilotapp.com", script_pattern: "sky_pilot.js", category: "Orders and shipping" }, { name: "Carts Guru", short_description: "Retargeting", app_store_url: "https://apps.shopify.com/cartsguru", website_url: "http://carts.guru", script_pattern: "api.carts.guru", category: "Sales" }, { name: "Kiwi Size Chart", short_description: "Manage all your size charts", app_store_url: "https://apps.shopify.com/kiwi-sizing", website_url: "", script_pattern: "kiwishopapps.com", category: "Store Design" }, { name: "Shop The Look", short_description: "Help your customers Buy the Look and purchase multiple items", app_store_url: "https://apps.shopify.com/shop-the-look-4", website_url: "https://shopthelookapp.com", script_pattern: "shopthelook.js", category: "Sales" }, { name: "Smart eu cookie banner", short_description: "Banner, Block Cookies", app_store_url: "https://apps.shopify.com/smart-eu-cookie-banner", website_url: "", script_pattern: "smarteucookiebanner.upsell-apps.com", category: "Trust and security" }, { name: "Broadcast Bar", short_description: "Display your broadcast news", app_store_url: "https://apps.shopify.com/broadcast-bar", website_url: "https://www.zestard.com", script_pattern: "broadcast-bar/public/js/newsticker-app.js", category: "Store Design" }, { name: "Getbread", short_description: "Place Bread checkout buttons", app_store_url: "https://shopify.getbread.com", website_url: "https://www.getbread.com", script_pattern: "shopify.getbread.com", category: "Store Design" }, { name: "ReConvert", short_description: "ReConvert post purchase", app_store_url: "https://apps.shopify.com/reconvert", website_url: "https://stilyoapps.info", script_pattern: "store_reconvert.js", category: "Sales" }, { name: "Sales Countdown Timer", short_description: "Countdown Timer", app_store_url: "https://apps.shopify.com/sales-countdown-timer-bar", website_url: "https://spur-i-t.com", script_pattern: "sales-countdown-timer/js/common.js", category: "Sales" }, { name: "Klevu Search", short_description: "Instant smart search", app_store_url: "https://apps.shopify.com/klevu-smart-search", website_url: "https://www.klevu.com", script_pattern: "js.klevu.com", category: "Store Design" }, { name: "AdNabu", short_description: "Google Ads", app_store_url: "https://apps.shopify.com/partners/adnabu-inc", website_url: "https://www.adnabu.com", script_pattern: "storage.googleapis.com/adnabu-shopify", category: "Marketing" }, { name: "Pop‑Up Builder", short_description: "Pop‑Up Builder", app_store_url: "https://apps.shopify.com/pop-up-builder", website_url: "https://www.lumifish.com", script_pattern: "lumifish-pop-up.appspot.com/popup.js", category: "Store Design" }, { name: "Add to cart button", short_description: "Add to cart button and buy button", app_store_url: "https://apps.shopify.com/add-to-cart", website_url: "https://www.goldendev.win/shopify/add-to-cart/support", script_pattern: "add-to-cart.js", category: "Store Design" }, { name: "ProFit", short_description: "Virtual Fitting Room For Online Fashion Stores", app_store_url: "https://apps.shopify.com/alomafit-vfr-light-1", website_url: "https://www.alomafit.com", script_pattern: ".alomafit.com/sticky_try.js", category: "Store Design" }, { name: "XE", short_description: "Currency Converter", app_store_url: "https://apps.shopify.com/xe-currency-converter", website_url: "https://www.xe.com", script_pattern: "xecurrency.js", category: "Store Design" }, { name: "All‑in‑one Bar", short_description: "Announcement bar", app_store_url: "https://apps.shopify.com/all-in-one-bar", website_url: "", script_pattern: "all-in-one-bar.js", category: "Store Design" }, { name: "Sitejabber", short_description: "Store Reviews", app_store_url: "https://apps.shopify.com/sitejabber-free-store-reviews-traffic-leads", website_url: "https://www.sitejabber.com", script_pattern: ".sitejabber.com", category: "Sales" }, { name: "Currency Converter", short_description: "Provide localized shopping experience, increase global sales", app_store_url: "https://apps.shopify.com/multi-currency-converter", website_url: "https://hextom.com", script_pattern: "lastsecondcoupon/js/multicurrencyconverter.js", category: "Store Design" }, { name: "Cool Image Magnifier", short_description: "Magnifier-like zoom for your product images", app_store_url: "https://apps.shopify.com/cool-image-magnifier", website_url: "https://www.codeblackbelt.com", script_pattern: ".codeblackbelt.com/js/modules/cool-image-magnifier", category: "Store Design" }, { name: "Bold Loyalty Points", short_description: "Flexible loyalty program", app_store_url: "https://apps.shopify.com/loyalty-points-by-bold", website_url: "https://boldcommerce.com/loyalty-points", script_pattern: "loy.boldapps.net", category: "Marketing" }, { name: "App1pro", short_description: "Related Products", app_store_url: "https://apps.shopify.com/related-products-pro", website_url: "http://app1pro.com", script_pattern: "app1pro.b-cdn.net/relatedproduct/js/relatedproduct.min.js", category: "Sales" }, { name: "Leadslide (Multiple possibilites)", short_description: "Coupon Popup, Upsells, Shipping Bar", app_store_url: "https://apps.shopify.com/partners/developer-dd332b77623f4d86", website_url: "https://leadslide.com", script_pattern: "leadslide-js", category: "Sales" }, { name: "Seguno", short_description: "Dynamic Banner Suite", app_store_url: "https://apps.shopify.com/coupon-banner-with-countdown-carousel", website_url: "https://www.seguno.com", script_pattern: ".seguno.com", category: "Store Design" }, { name: "Countdown Timer", short_description: "Add Countdown Timer your Store & generate Urgency", app_store_url: "https://apps.shopify.com/cowntdown-timer-by-revy", website_url: "https://revy.io", script_pattern: "api.revy.io/timer.js", category: "Sales" }, { name: "Revy - UpSell", short_description: "Increase & Maximize average order value and sales with UpSell", app_store_url: "https://apps.shopify.com/sales-booster-upsell-cross-sell-by-revy-shopify-apps", website_url: "https://revy.io", script_pattern: "api.revy.io/upsell.js", category: "Sales" }, { name: "Hide PayPal in Cart", short_description: "Hide PayPal button to improve customer checkout experience", app_store_url: "https://apps.shopify.com/hide-paypal-in-cart", website_url: "https://inscoder.com", script_pattern: "hidepaypal2-static.inscoder.com", category: "Store Design" }, { name: "Secomapp Currency Switcher", short_description: "Currency Switcher", app_store_url: "https://apps.shopify.com/currency-switcher", website_url: "https://www.secomapp.com/currency-switcher-app", script_pattern: "cdn.secomapp.com/currency_switcher", category: "Store Design" }, { name: "Cart Activity", short_description: "Get a newsfeed of what shoppers are doing on your site", app_store_url: "https://apps.shopify.com/cart-activity", website_url: "https://www.secomapp.com/currency-switcher-app", script_pattern: ".cartactivity.com/assets/recent_activities.js", category: "Sales" }, { name: "Panda", short_description: "Language Translate", app_store_url: "https://apps.shopify.com/translate", website_url: "https://pandaapps.in", script_pattern: "pandaapps.in/apps/languagepanda", category: "Store Design" }, { name: "Lifter Apps", short_description: "Pop‑Up Window", app_store_url: "https://apps.shopify.com/pop-up-window", website_url: "https://lifterapps.com", script_pattern: "popup4.lifterpopup.com", category: "Marketing" }, { name: "AutoCommerce", short_description: "Amazon-like product recommendations", app_store_url: "https://apps.shopify.com/orcinus-product-recommendation", website_url: "http://autocommerce.io", script_pattern: "rec.autocommerce.io/recommender_javascript", category: "Sales" }, { name: "WooHoo", short_description: "Gamified Email Popups", app_store_url: "https://apps.shopify.com/woohoo", website_url: "https://getwoohoo.com", script_pattern: "app.getwoohoo.com", category: "Sales" }, { name: "Tidio.co", short_description: "Live chat boosted with Bots and Marketing Automation", app_store_url: "https://apps.shopify.com/tidio-chat", website_url: "http://tidio.co", script_pattern: "code.tidio.co", category: "Customer service" }, { name: "Upsell - KAD Systems", short_description: "Generate more sales through upsells with our simple upsell app", app_store_url: "https://apps.shopify.com/upsell-system", website_url: "https://kad.systems", script_pattern: "upsell.kad.systems", category: "Sales" }, { name: "Nextsale", short_description: "Social Proof, Increase Sales Pop Timers Social Proof and hurry", app_store_url: "https://apps.shopify.com/nextsale", website_url: "https://nextsale.io", script_pattern: "cdn.nextsale.io", category: "Sales" }, { name: "Revy Unlimited Bundles", short_description: "Bundle products together with discounts and make more sales!", app_store_url: "https://apps.shopify.com/product-bundles-discounts-by-revy", website_url: "https://revy.io", script_pattern: "api.revy.io/bundle.js", category: "Store Design" }, { name: "NDNAPPS Banner Slider", short_description: "Responsive banner slider, slideshow, image gallery", app_store_url: "https://apps.shopify.com/banner-slider-1", website_url: "https://www.ndnapps.com", script_pattern: "ndnapps.com/ndnapps/banner-slider", category: "Store Design" }, { name: "Volume and Tiered Discounts", short_description: "Ultimate Quantity Discounts & Tiered Pricing Rule for Products", app_store_url: "https://apps.shopify.com/volume-discount-by-hulkapps", website_url: "https://www.hulkapps.com", script_pattern: "volumediscount.hulkapps.com", category: "Sales" }, { name: "Trust Badge Master", short_description: "Establish trust and security to increase sales conversions", app_store_url: "https://apps.shopify.com/badge-master-by-hulkapps", website_url: "https://www.hulkapps.com", script_pattern: "badgemaster.hulkapps.com", category: "Sales" }, { name: "Ultimate Upsell", short_description: "Upsell Bundles, Before Checkout or After Payment", app_store_url: "https://apps.shopify.com/ultimate-upsell", website_url: "https://tabarnapp.com/ultimate-upsell-shopify", script_pattern: "ultimate-upsells/selectorTool.min.js", category: "Sales" }, { name: "Advanced Bundle Products", short_description: "Product bundles: make higher value offers and get more sales!", app_store_url: "https://apps.shopify.com/grouped-products", website_url: "https://appstore.mageworx.com", script_pattern: "files-shpf.mageworx.com/groupedproducts", category: "Sales" }, { name: "Message Mate Texting Platform", short_description: "Convert more customers with the convenience of texting", app_store_url: "https://apps.shopify.com/message-mate", website_url: "https://ownerlistens.com", script_pattern: "ownerlistens.com", category: "Sales" }, { name: "OrderLogic", short_description: "Simple min and max product and order limits plus much more", app_store_url: "https://apps.shopify.com/orderlogic", website_url: "https://www.orderlogicapp.com", script_pattern: "orderlogicapp.com", category: "Store Design" }, { name: "EU Cookie Bar", short_description: "Provide a cookie bar to European customers", app_store_url: "https://apps.shopify.com/eu-cookie-bar", website_url: "", script_pattern: "booster-eu-cookie", category: "Sales" }, { name: "Omega Instant Search", short_description: "Improve store search and boost your sales", app_store_url: "https://apps.shopify.com/omega-instant-search", website_url: "https://omegacommerce.com/search", script_pattern: "search.omegacommerce.com", category: "Store Design" }, { name: "Sales Notifications pop up", short_description: "Recent Sales Notifications popup for urgency and social proof", app_store_url: "https://apps.shopify.com/livebar", website_url: "", script_pattern: "app.livebar.io", category: "Sales" }, { name: "GDPR Cookie Compiler", short_description: "Get GDPR Cookie Compliance Easier", app_store_url: "https://apps.shopify.com/eu-cookie-compiler", website_url: "https://www.metizsoft.com", script_pattern: "metizapps.com/eucookie", category: "Trust and Security" }, { name: "Sales Pop up Notifications", short_description: "Sales Pop to boost sale & social proof with live sales pop up", app_store_url: "https://apps.shopify.com/recent-sales-popup-notifications-1", website_url: "https://carecart.io", script_pattern: "sales-pop.carecart.io/lib/salesnotifier.js", category: "Sales" }, { name: "Pixel Union Ultimate Special Offers", short_description: "All your sales, discounts, and promotions in one place", app_store_url: "https://apps.shopify.com/special-offers", website_url: "https://www.pixelunion.net", script_pattern: "storefront.cdn.pxu.co/apps/uso.js", category: "Sales" }, { name: "Product Discount", short_description: "Quantity Discounts/Tiered, Countdown Timer, Stock Countdown", app_store_url: "https://apps.shopify.com/discount-master", website_url: "https://autoketing.com", script_pattern: "product-discount-dot-autoketing-production-sdk.appspot.com/dist/product-discount-embed.js", category: "Sales" }, { name: "Upsell Cross‑Sell", short_description: "Upsell Product, Cross-sell, Discounted Upsells, Upsell Bundles", app_store_url: "https://apps.shopify.com/upsell-cross-sell-smart-tool", website_url: "https://autoketing.com", script_pattern: "upsell-master-dot-autoketing-production-sdk.appspot.com/dist/upsell-master-embed.js", category: "Sales" }, { name: "Instant Brand Page", short_description: "A-Z Brand Index Page and Favourites Slider", app_store_url: "https://apps.shopify.com/instant-brand-page", website_url: "http://lowfruitsolutions.com", script_pattern: "cdn.instantbrandpage.lowfruitsolutions.com", category: "Sales" }, { name: "Back In Stock by Appikon", short_description: "Back In Stock product notifications via email, SMS, FB Messenger and Push", app_store_url: "https://apps.shopify.com/customer-back-in-stock-alert-user-notification-app", website_url: "http://appikon.com", script_pattern: "subscribe-it.js", }, { name: "Okendo", short_description: "Product reviews", app_store_url: "https://apps.shopify.com/okendo-reviews", website_url: "https://www.okendo.io/", script_pattern: "reviewsWidget.min.js", category: "Sales" }, { name: "Hulk Apps Reviews", short_description: "Product reviews", app_store_url: "https://apps.shopify.com/product-reviews-by-hulkapps", website_url: "https://www.hulkapps.com/blogs/product-reviews/", script_pattern: "reviews-by-hulkapps.js", category: "Sales" }, { name: "Reviews.io", short_description: "Product reviews", app_store_url: "https://apps.shopify.com/reviews-co-uk-product-and-merchant-review-collection", website_url: "https://www.reviews.io", script_pattern: ".reviews.io", category: "Sales" }, { name: "Junip", short_description: "Product reviews", app_store_url: "https://apps.shopify.com/junip", website_url: "https://www.juniphq.com", script_pattern: "scripts.juniphq.com", }, { name: "GeReviews", short_description: "Product reviews", app_store_url: "https://apps.shopify.com/getreviews", website_url: "https://www.dsreviews.net", script_pattern: "api.dsreviews.net", }, { name: "BF Size Charts & Size Guides", short_description: "Add size charts to your product pages", app_store_url: "https://apps.shopify.com/size-charts-by-relentless", website_url: "https://www.relentlessapps.com", script_pattern: "size-charts-relentless.js", category: "Store Design" }, { name: "PickyStory", short_description: "Automate Upsell & Cross-Sell of Bundles, Kits, and Looks", long_description: "Generate more revenue from every store visit. Sell Shopify product Bundles, Kits, and Looks with one app. It’s easy and done in a few clicks.", app_store_url: "https://apps.shopify.com/product-kits-bundles-pickystory", website_url: "https://pickystory.com/", category: "Sales", script_pattern: /cdn\.pickystory\.com\/widget\/dist\/latest\/pickystory-widget\.min\.js/, }, { name: "Vitals", short_description: "Combo app: Upsells, Reviews, Bundles, BOGO, etc", app_store_url: "https://apps.shopify.com/vitals", website_url: "https://www.vitals.co", script_pattern: "appsolve.io", }, { name: "Aftership", short_description: "Shipping tracking", app_store_url: "https://apps.shopify.com/aftership", website_url: "https://www.aftership.com", script_pattern: "aftership.", }, { name: "CJ Dropshipping", short_description: "Helps sites that source from CJ Dropshipping", app_store_url: "https://apps.shopify.com/cucheng", website_url: "https://www.cjdropshipping.com", script_pattern: "app.cjdropshipping.", } ];
$(function () { $("#jqGrid").jqGrid({ url: '/admin/carousels/list', datatype: "json", colModel: [ {label: 'id', name: 'carouselId', index: 'carouselId', width: 50, key: true, hidden: true}, {label: '轮播图', name: 'carouselUrl', index: 'carouselUrl', width: 180, formatter: coverImageFormatter}, {label: '跳转链接', name: 'redirectUrl', index: 'redirectUrl', width: 120}, {label: '排序值', name: 'carouselRank', index: 'carouselRank', width: 120}, {label: '添加时间', name: 'createTime', index: 'createTime', width: 120} ], height: 560, rowNum: 10, rowList: [10, 20, 50], styleUI: 'Bootstrap', loadtext: '信息读取中...', rownumbers: false, rownumWidth: 20, autowidth: true, multiselect: true, pager: "#jqGridPager", jsonReader: { root: "data.list", page: "data.currPage", total: "data.totalPage", records: "data.totalCount" }, prmNames: { page: "page", rows: "limit", order: "order", }, gridComplete: function () { //隐藏grid底部滚动条 $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"}); } }); function coverImageFormatter(cellvalue) { return "<img src='" + cellvalue + "' height=\"120\" width=\"160\" alt='coverImage'/>"; } $(window).resize(function () { $("#jqGrid").setGridWidth($(".card-body").width()); }); new AjaxUpload('#uploadCarouselImage', { action: '/admin/upload/file', name: 'file', autoSubmit: true, responseType: "json", onSubmit: function (file, extension) { if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))) { alert('只支持jpg、png、gif格式的文件!'); return false; } }, onComplete: function (file, r) { if (r != null && r.resultCode == 200) { $("#carouselImg").attr("src", r.data); $("#carouselImg").attr("style", "width: 128px;height: 128px;display:block;"); return false; } else { alert("error"); } } }); }); /** * jqGrid重新加载 */ function reload() { var page = $("#jqGrid").jqGrid('getGridParam', 'page'); $("#jqGrid").jqGrid('setGridParam', { page: page }).trigger("reloadGrid"); } function carouselAdd() { reset(); $('.modal-title').html('轮播图添加'); $('#carouselModal').modal('show'); } //绑定modal上的保存按钮 $('#saveButton').click(function () { var redirectUrl = $("#redirectUrl").val(); var carouselRank = $("#carouselRank").val(); var carouselUrl = $('#carouselImg')[0].src; var data = { "carouselUrl": carouselUrl, "carouselRank": carouselRank, "redirectUrl": redirectUrl }; var url = '/admin/carousels/save'; var id = getSelectedRowWithoutAlert(); if (id != null) { url = '/admin/carousels/update'; data = { "carouselId": id, "carouselUrl": carouselUrl, "carouselRank": carouselRank, "redirectUrl": redirectUrl }; } $.ajax({ type: 'POST',//方法类型 url: url, contentType: 'application/json', data: JSON.stringify(data), success: function (result) { if (result.resultCode == 200) { $('#carouselModal').modal('hide'); swal("保存成功", { icon: "success", }); reload(); } else { $('#carouselModal').modal('hide'); swal(result.message, { icon: "error", }); } ; }, error: function () { swal("操作失败", { icon: "error", }); } }); }); function carouselEdit() { reset(); var id = getSelectedRow(); if (id == null) { return; } //请求数据 $.get("/admin/carousels/info/" + id, function (r) { if (r.resultCode == 200 && r.data != null) { //填充数据至modal $("#carouselImg").attr("src", r.data.carouselUrl); $("#carouselImg").attr("style", "height: 64px;width: 64px;display:block;"); $("#redirectUrl").val(r.data.redirectUrl); $("#carouselRank").val(r.data.carouselRank); } }); $('.modal-title').html('轮播图编辑'); $('#carouselModal').modal('show'); } function deleteCarousel() { var ids = getSelectedRows(); if (ids == null) { return; } swal({ title: "确认弹框", text: "确认要删除数据吗?", icon: "warning", buttons: true, dangerMode: true, }).then((flag) = > { if (flag) { $.ajax({ type: "POST", url: "/admin/carousels/delete", contentType: "application/json", data: JSON.stringify(ids), success: function (r) { if (r.resultCode == 200) { swal("删除成功", { icon: "success", }); $("#jqGrid").trigger("reloadGrid"); } else { swal(r.message, { icon: "error", }); } } }); } } ) ; } function reset() { $("#redirectUrl").val('##'); $("#carouselRank").val(0); $("#carouselImg").attr("src", '/admin/dist/img/img-upload.png'); $("#carouselImg").attr("style", "height: 64px;width: 64px;display:block;"); $('#edit-error-msg').css("display", "none"); }
import React from "react" import styled from "@emotion/styled" import ShellWrapper from "./ShellWrapper" import { palette, breakpoints, spacings } from "../utils/variables" const SplitWrapper = ({ children }) => ( <Wrapper> <FlexWrapper>{children}</FlexWrapper> </Wrapper> ) export const Wrapper = styled.div` position: relative; @media (min-width: ${breakpoints.mobile}) { &::before { content: ""; position: absolute; background-color: ${palette.lightGrey}; top: 0; left: 0; bottom: 0; right: 50%; z-index: 0; } } ` const FlexWrapper = styled.div` align-items: flex-start; display: flex; flex-flow: column nowrap; margin: auto; max-width: ${spacings.maxWidth}; position: relative; width: 100%; z-index: 1; @media (min-width: ${breakpoints.mobile}) { flex-flow: row nowrap; } ` export const Sidebar = styled(ShellWrapper)` background-color: ${palette.lightGrey}; margin-bottom: 20px; @media (min-width: ${breakpoints.mobile}) { position: sticky; top: -28px; margin-bottom: 0; flex: 0 0 350px; } ` export const Main = styled(ShellWrapper)` background-color: ${palette.white}; ` export default Object.assign(SplitWrapper, { Sidebar, Main })