Skip to content

Commit

Permalink
fix(core): 将整个项目修改成跨域响应式模式
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed Jun 11, 2022
1 parent d7f967e commit 10aaf0a
Show file tree
Hide file tree
Showing 14 changed files with 147 additions and 100 deletions.
29 changes: 19 additions & 10 deletions packages/core/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
>
<div class="alert-container">
<template
v-for="(item,index) of ctx.common.alerts"
v-for="(item,index) of local.alerts"
:key="index"
>
<Alert
:style="{opacity: 1 - (ctx.common.alerts.length - 1 - index) * (1/ctx.common.alerts.length)}"
:style="{opacity: 1 - (local.alerts.length - 1 - index) * (1/local.alerts.length)}"
:type="item.type"
:text="item.text"
:index="index"
Expand Down Expand Up @@ -39,7 +39,7 @@
class="ocs-panel-header draggable"
>
<template
v-for="(item, index) in currentPanels"
v-for="(item, index) in currentPanels.filter(p=>p.hide !== true)"
:key="index"
>
<div
Expand All @@ -59,7 +59,7 @@
class="ocs-panel-container"
>
<template
v-for="(item, index) in currentPanels"
v-for="(item, index) in currentPanels.filter(p=>p.hide !== true)"
:key="index"
>
<div
Expand Down Expand Up @@ -88,6 +88,7 @@

<script setup lang="ts">
import { computed, Ref } from '@vue/reactivity';
import debounce from 'lodash/debounce';
import { nextTick, onMounted, ref, watch } from 'vue';
import { Alert } from './components/alert';
import { Tooltip } from './components/Tooltip';
Expand Down Expand Up @@ -120,7 +121,8 @@ const currentPanels = computed(() => {
/**
* 当前面板的 key
*/
const activeKey = ref(currentPanels.value[0]?.name);
const activeKey = ref(currentPanels.value
.find((p) => p.name === local.activeKey)?.name || currentPanels.value[0]?.name);
/**
* 元素
*/
Expand All @@ -140,6 +142,10 @@ watch(currentPanels, () => {
}
});
watch(activeKey, () => {
local.activeKey = activeKey.value;
});
watch(hide, () => {
local.hide = hide.value;
nextTick(() => {
Expand All @@ -148,6 +154,9 @@ watch(hide, () => {
});
onMounted(() => {
// 清理提醒
local.alerts = [];
nextTick(() => {
listenResetEvent();
enablePanelDrag();
Expand Down Expand Up @@ -178,6 +187,11 @@ onMounted(() => {
});
});
const onMove = debounce(function(x: number, y: number) {
local.position.x = x;
local.position.y = y;
}, 100);
/**
* 启用面板拖拽
*/
Expand All @@ -193,11 +207,6 @@ function enablePanelDrag() {
}
}
function onMove(x: number, y: number) {
local.position.x = x;
local.position.y = y;
}
/**
* 监听重置位置
*/
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/components/Alert.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineComponent, PropType, toRefs } from 'vue';
import { useContext } from '../store';
import { useStore } from '../store';
import { AlertType } from './types';

export const Alert = defineComponent({
Expand All @@ -19,15 +19,15 @@ export const Alert = defineComponent({
},
setup(props) {
const { type, text, index } = toRefs(props);
const { common } = useContext();
const local = useStore('localStorage');

return () => (
<div class={['alert', type.value].join(' ')}>
<span style="text-shadow: 0 0 BLACK;">{ type.value === 'info' ? 'ℹ️' : type.value === 'error' ? '❗' : type.value === 'success' ? '✅' : type.value === 'warn' ? '⚠️' : '❕' }</span>
<div style="display: inline">
<span
class="alert-closer"
onClick={() => (common.alerts.splice(index.value, 1))}>
onClick={() => (local.alerts.splice(index.value, 1))}>
×
</span>
<span class="alert-text">{ text.value }</span>
Expand Down
12 changes: 4 additions & 8 deletions packages/core/src/components/SearchResults.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { computed, defineComponent, onMounted, Ref, ref } from 'vue';
import { WorkResult } from '../core/worker/interface';
import { useContext } from '../store';
import { useStore } from '../store';
import { Tooltip } from './Tooltip';
import { StringUtils } from '@ocsjs/common/src/utils/string';

export const SearchResults = defineComponent({
setup () {
const { common } = useContext();
const local = useStore('localStorage');
// 判断是否有搜索结果
const validResult = computed(() => common.workResults);
const hasResult = computed(() => validResult.value.length > 0);
const hasResult = computed(() => local.workResults.length > 0);
// 当前搜索对象
const currentResult: Ref<WorkResult<any> | undefined> = ref(undefined);
// 当前展示的结果
Expand All @@ -22,9 +21,6 @@ export const SearchResults = defineComponent({
);

onMounted(() => {
// 清空搜索结果
common.workResults = [];

// 监听页面点击事件,然后关闭搜索悬浮窗
document.addEventListener('click', () => {
currentResult.value = undefined;
Expand Down Expand Up @@ -127,7 +123,7 @@ export const SearchResults = defineComponent({
<hr />

<div>
{validResult.value.map((res, i) => {
{local.workResults.map((res, i) => {
const title = res.ctx?.elements.title?.[0];

const isCopy = ref(false);
Expand Down
14 changes: 2 additions & 12 deletions packages/core/src/components/cx/StudySettingPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import { defineComponent } from 'vue';
import { createWorkerSetting } from '..';

import { fixedVideoProgress, switchPlayLine } from '../../script/cx/study';
import { useContext, useSettings } from '../../store';
import { fixedVideoProgress } from '../../script/cx/study';
import { useSettings } from '../../store';
import { Tooltip } from '../Tooltip';
import { CommonWorkSettingPanel } from './CommonWorkSettingPanel';

export const StudySettingPanel = defineComponent({
setup () {
const settings = useSettings().cx.study;
const ctx = useContext();
const workSettings = useSettings().cx.work;

return () => (
Expand All @@ -26,9 +23,6 @@ export const StudySettingPanel = defineComponent({
step="0.25"
onInput={(e: any) => {
settings.playbackRate = e.target.valueAsNumber;
if (ctx.common.currentMedia) {
ctx.common.currentMedia.playbackRate = e.target.valueAsNumber;
}
}}
></input>
</Tooltip>
Expand All @@ -45,7 +39,6 @@ export const StudySettingPanel = defineComponent({
value={settings.volume}
onInput={(e: any) => {
settings.volume = e.target.valueAsNumber;
if (ctx.common.currentMedia) ctx.common.currentMedia.volume = e.target.valueAsNumber;
}}
/>
<span> {Math.round(settings.volume * 100)}% </span>
Expand All @@ -59,9 +52,6 @@ export const StudySettingPanel = defineComponent({
value={settings.line || '默认路线'}
onChange={(e: any) => {
settings.line = e.target.value;
if (ctx.cx.videojs && ctx.common.currentMedia) {
switchPlayLine(settings, ctx.cx.videojs, ctx.common.currentMedia, e.target.value);
}
}}
>
{settings.playlines.map((line: any) => (
Expand Down
10 changes: 5 additions & 5 deletions packages/core/src/components/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@

import { useContext } from '../store';
import { useStore } from '../store';
import { AlertType } from './types';

export function message(type: AlertType['type'], text: string) {
const { common } = useContext();
if (common.alerts.length > 3) {
common.alerts.shift();
const local = useStore('localStorage');
if (local.alerts.length > 3) {
local.alerts.shift();
}
common.alerts.push({ type, text, key: common.alerts.length });
local.alerts.push({ type, text, key: local.alerts.length });
}
2 changes: 2 additions & 0 deletions packages/core/src/core/define.script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export interface ScriptPanel {
priority?: number
/** 当页面没有任何面板时,显示的默认面板 */
default?: boolean
/** 是否隐藏 */
hide?: boolean
}

export type ScriptPanelChild = Omit<ScriptPanel, 'url' | 'children'>
Expand Down
12 changes: 6 additions & 6 deletions packages/core/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { WorkResult } from './worker/interface';
* OCS 本地存储类型
*/
export interface OCSLocalStorage {
[x: string]: any
/** 网课平台类型 */
platform?: string
/** 本地设置 */
Expand All @@ -17,14 +16,19 @@ export interface OCSLocalStorage {
hide: boolean
/** 面板位置 */
position: { x: number; y: number }
/** 面板当前的页面 */
activeKey: string
/** 日志存储 */
logs: {
time: number
level: string
extra: string
text: string
}[]

/** 消息 */
alerts: AlertType[]
/** 搜索结果存储 */
workResults: WorkResult<any>[]
}

export interface OCSStore {
Expand All @@ -36,12 +40,8 @@ export interface OCSStore {
common: {
/** 当前视频 */
currentMedia: HTMLMediaElement | null
/** 搜索结果存储 */
workResults: WorkResult<any>[]
/** 启动参数 */
startOptions: StartOptions | undefined
/** 消息 */
alerts: AlertType[]
},
/**
* 各脚本预留存储字段
Expand Down
13 changes: 12 additions & 1 deletion packages/core/src/core/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function getCurrentRoutes(scripts: DefineScript[]): ScriptRoute[] {
* 当前面板
*/
export function getCurrentPanels(scripts: DefineScript[]) {
let panels: Pick<ScriptPanel, 'name' | 'el' | 'default' | 'priority'>[] = [];
let panels: Pick<ScriptPanel, 'name' | 'el' | 'default' | 'priority' | 'hide'>[] = [];
for (const script of scripts) {
for (const panel of script.panels || []) {
if (urlMatch(panel.url)) {
Expand Down Expand Up @@ -133,3 +133,14 @@ export async function getRemoteSetting(port: number) {
await sleep(60 * 1000);
}
}

/**
* 使元素变成纯文本对象,(跨域时对象上下文会被销毁)
*/
export function elementToRawObject(el: HTMLElement) {
return {
innerText: el.innerText,
innerHTML: el.innerHTML,
textContent: el.textContent
} as any;
}
11 changes: 6 additions & 5 deletions packages/core/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isInBrowser } from './core/utils';
import { useStore } from './store';

export function loggerPrefix(level: 'info' | 'error' | 'warn' | 'debug') {
Expand Down Expand Up @@ -25,7 +26,7 @@ export function logger(level: 'info' | 'error' | 'warn' | 'debug', ...msg: any[]
if (level === 'error') {
console.error(...createLog(level, msg));
}
if (document) {
if (isInBrowser()) {
const extra =
level === 'info'
? '信息'
Expand All @@ -40,13 +41,13 @@ export function logger(level: 'info' | 'error' | 'warn' | 'debug', ...msg: any[]
const type = typeof s;
return type === 'function' ? '[Function]' : type === 'object' ? '[Object]' : type === 'undefined' ? '无' : s;
});
const logs = useStore('localStorage').logs;
const local = useStore('localStorage');

if (logs.length > 50) {
logs.shift();
if (local.logs.length > 50) {
local.logs.shift();
}

logs.push({
local.logs.push({
time: Date.now(),
level,
extra,
Expand Down
17 changes: 10 additions & 7 deletions packages/core/src/script/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createNote } from '../../components';
import { defineScript } from '../../core/define.script';
import { getRemoteSetting, onComplete, onInteractive, useUnsafeWindow } from '../../core/utils';
import { logger } from '../../logger';
import { definedScripts } from '../../main';
import { useSettings } from '../../store';

const supports = ['*'];
Expand Down Expand Up @@ -65,13 +66,13 @@ export const CommonScript = defineScript({
url: supports,
async onload() {
if (top === self) {
const { common } = useSettings();
if (common.answererWrappers.length === 0) {
const settings = useSettings();
if (settings.common.answererWrappers.length === 0) {
const setting = await getRemoteSetting(15319);
if (setting?.answererWrappers) {
logger('debug', '成功读取本地题库配置');
const { common } = useSettings();
common.answererWrappers = setting.answererWrappers;
const settings = useSettings();
settings.common.answererWrappers = setting.answererWrappers;
}
}
}
Expand All @@ -86,9 +87,11 @@ export const CommonScript = defineScript({
url: supports,
el: () =>
createNote(
'提示: 手动点击进入视频,作业,考试页面,即可自动运行',
'注意! 请将浏览器页面保持最大化,或者缩小,但是不能最小化,可能导致视频播放错误!',
'拖动上方标题栏可以进行拖拽'
'⭐ 脚本列表:' + definedScripts.map(s => s.name).join(', '),
'📢 手动点击进入视频,作业,考试页面,即可自动运行',
'📢 如果进入后未显示任何设置或者未运行,则您当前的页面或者网课没有脚本哦。',
'⚠️ 请将浏览器页面保持最大化,或者缩小窗口,不能最小化,可能导致视频,ppt等任务不能运行!',
'💡 拖动上方标题栏可以进行拖拽哦!'
)
}
]
Expand Down
Loading

0 comments on commit 10aaf0a

Please sign in to comment.