diff --git a/.idea/FristProject.iml b/.idea/FristProject.iml index a35650a..835a31e 100644 --- a/.idea/FristProject.iml +++ b/.idea/FristProject.iml @@ -2,7 +2,7 @@ <module type="PYTHON_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://$MODULE_DIR$" /> - <orderEntry type="jdk" jdkName="acl392" jdkType="Python SDK" /> + <orderEntry type="jdk" jdkName="Remote Python 3.9.2 (sftp://root@192.168.3.103:22/usr/local/miniconda3/bin/python)" jdkType="Python SDK" /> <orderEntry type="sourceFolder" forTests="false" /> </component> </module> \ No newline at end of file diff --git a/.idea/deployment.xml b/.idea/deployment.xml index a770801..e886ec8 100644 --- a/.idea/deployment.xml +++ b/.idea/deployment.xml @@ -1,7 +1,14 @@ <?xml version="1.0" encoding="UTF-8"?> <project version="4"> - <component name="PublishConfigData" autoUpload="Always" serverName="root@192.168.3.48:22" remoteFilesAllowedToDisappearOnAutoupload="false"> + <component name="PublishConfigData" autoUpload="Always" serverName="root@192.168.3.103:22" remoteFilesAllowedToDisappearOnAutoupload="false"> <serverData> + <paths name="root@192.168.3.103:22"> + <serverdata> + <mappings> + <mapping deploy="/mnt/zfbox" local="$PROJECT_DIR$" /> + </mappings> + </serverdata> + </paths> <paths name="root@192.168.3.48:22"> <serverdata> <mappings> diff --git a/.idea/misc.xml b/.idea/misc.xml index 7269ac0..3c03da2 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -3,7 +3,7 @@ <component name="Black"> <option name="sdkName" value="PyTorch" /> </component> - <component name="ProjectRootManager" version="2" project-jdk-name="acl392" project-jdk-type="Python SDK" /> + <component name="ProjectRootManager" version="2" project-jdk-name="Remote Python 3.9.2 (sftp://root@192.168.3.103:22/usr/local/miniconda3/bin/python)" project-jdk-type="Python SDK" /> <component name="PyCharmProfessionalAdvertiser"> <option name="shown" value="true" /> </component> diff --git a/config.yaml b/config.yaml index 959b2ce..a62e697 100644 --- a/config.yaml +++ b/config.yaml @@ -23,15 +23,16 @@ pw: zfkj_123!@# MAX_CONTENT_LENGTH : 100 # 100MB UPLOAD_FOLDER : uploads ALLOWED_EXTENSIONS : {'zip'} +Model_Plugins: model/plugins #RTSP RTSP_Check_Time : 600 #10分钟 -- 2024-7-8 取消使用 #max_channel_num -max_channel_num : 4 #最大视频通道数量 +max_channel_num : 8 #最大视频通道数量 #model -model_platform : cpu #acl gpu cpu +model_platform : acl #acl gpu cpu device_id : 0 #单设备配置 weight_path: /model/weights yolov5_path: D:/Project/FristProject/model/base_model/yolov5 #使用绝对路径,不同的部署环境需要修改! @@ -43,3 +44,7 @@ verify_rate : 8 #验证帧率--- 也就是视频输出的帧率 warn_video_path: /mnt/zfbox/model/warn/ warn_interval: 120 #报警间隔--单位秒 video_error_count: 3 #单位秒 ---根据验证帧率,判断3秒内都是空帧的话,视频源链接有问题。 + +#system --- 指定网卡 +wired_interface : eth0 +wireless_interface : WLAN diff --git a/core/CapManager.py b/core/CapManager.py new file mode 100644 index 0000000..37168e6 --- /dev/null +++ b/core/CapManager.py @@ -0,0 +1,121 @@ +import math +import queue +import cv2 +import threading +import time +from myutils.ConfigManager import myCongif +import subprocess as sp + +class VideoCaptureWithFPS: + '''视频捕获的封装类,是一个通道一个''' + def __init__(self, source): + self.source = source + self.width = None + self.height = None + # GStreamer --- 内存占用太高,且工作环境的部署也不简单 + # self.pipeline = ( + # "rtspsrc location=rtsp://192.168.3.102/live1 protocols=udp latency=100 ! " + # "rtph264depay !" + # " h264parse !" + # " avdec_h264 !" + # " videoconvert !" + # " appsink" + # ) + #self.cap = cv2.VideoCapture(self.pipeline, cv2.CAP_GSTREAMER) + + #FFmpeg --更加定制化的使用--但要明确宽高。。。 + # self.ffmpeg_cmd = [ + # 'ffmpeg', + # '-rtsp_transport', 'udp', + # '-i', 'rtsp://192.168.3.102/live1', + # '-f', 'image2pipe', + # '-pix_fmt', 'bgr24', + # '-vcodec', 'rawvideo', '-' + # ] + # self.pipe = sp.Popen(self.ffmpeg_cmd, stdout=sp.PIPE, bufsize=10 ** 8) + + # opencv -- 后端默认使用的就是FFmpeg -- 不支持UDP + self.cap = cv2.VideoCapture(self.source) + if self.cap.isOpened(): #若没有打开成功,在读取画面的时候,已有判断和处理 -- 这里也要检查下内存的释放情况 + self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + print(self.width,self.height) + #self.fps = fps # 线程保持最大帧率的刷新画面---过高的帧率会影响CPU性能,但过地的帧率会造成帧积压 + self.fps = math.ceil(self.cap.get(cv2.CAP_PROP_FPS)/float(myCongif.get_data("verify_rate")))-1 #向上取整。 + #print(self.fps) + self.running = True + self.frame_queue = queue.Queue(maxsize=1) + #self.frame = None + #self.read_lock = threading.Lock() + self.thread = threading.Thread(target=self.update) + self.thread.start() + + def update(self): + icount = 0 + while self.running: + ret, frame = self.cap.read() + if not ret: + icount += 1 + if icount > 5: #重连 + self.cap.release() + self.cap = cv2.VideoCapture(self.source) + #self.cap = cv2.VideoCapture(self.pipeline, cv2.CAP_GSTREAMER) + if self.cap.isOpened(): + self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + print(self.width,self.height) + # self.fps = fps # 线程保持最大帧率的刷新画面---过高的帧率会影响CPU性能,但过地的帧率会造成帧积压 + self.fps = math.ceil( + self.cap.get(cv2.CAP_PROP_FPS) / float(myCongif.get_data("verify_rate"))) -1 # 向上取整。 + icount = 0 + else: + #self.frame = None + sleep_time = myCongif.get_data("cap_sleep_time") + print(f"{self.source}视频流,将于{sleep_time}秒后重连!") + time.sleep(sleep_time) + continue + #resized_frame = cv2.resize(frame, (int(self.width / 2), int(self.height / 2))) + # with self.read_lock: + # self.frame = frame + if self.frame_queue.full(): + try: + #print("采集线程丢帧") + self.frame_queue.get(timeout=0.01) #这里不get的好处是,模型线程不会有None + except queue.Empty: #为空不处理 + pass + self.frame_queue.put(frame) + + # 跳过指定数量的帧以避免积压 + for _ in range(self.fps): + self.cap.grab() + # time.sleep(self.fps) #按照视频源的帧率进行休眠 + #print("Frame updated at:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + + def read(self): + ''' + 直接读视频原画面 + :param type: 0-大多数情况读取,1-绘制区域时读取一帧,但当前帧不丢,还是回队列 + :return: + ''' + # with self.read_lock: + # frame = self.frame.copy() if self.frame is not None else None + # if frame is not None: + # return True, frame + # else: + # return False, None + + if not self.frame_queue.empty(): + try: + frame = self.frame_queue.get(timeout=0.05) + except queue.Empty: + #print("cap-frame None") + return False, None + else: + #print("cap-frame None") + return False, None + return True, frame + + def release(self): + self.running = False + self.thread.join() + self.cap.release() \ No newline at end of file diff --git a/core/ChannelManager.py b/core/ChannelManager.py index e39710b..06a57e8 100644 --- a/core/ChannelManager.py +++ b/core/ChannelManager.py @@ -4,19 +4,25 @@ import numpy as np import time import copy import queue +import cv2 +import asyncio class ChannelData: def __init__(self, str_url, int_type, bool_run, deque_length,icount_max): - self.cap = None + self.cap = None #该通道视频采集对象 + self.work_th = None #该通道工作线程句柄 + self.b_model = False #是否有运行模型线程 + self.bool_run = bool_run # 线程运行标识 + self.str_url = str_url #视频源地址 self.int_type = int_type #视频源类型,0-usb,1-rtsp,2-hksdk - self.bool_run = bool_run #线程运行标识 - self.deque_frame = deque(maxlen=deque_length) + self.icount_max = icount_max # 帧序列号上限 + self.lock = threading.RLock() # 用于保证线程安全 + + self.deque_frame = deque(maxlen=deque_length) #视频缓冲区用于保存录像 self.last_frame = None # 保存图片数据 self.frame_queue = queue.Queue(maxsize=1) self.counter = 0 #帧序列号--保存报警录像使用 - self.icount_max = icount_max #帧序列号上限 - self.lock = threading.RLock() # 用于保证线程安全 #添加一帧图片 def add_deque(self, value): @@ -28,26 +34,53 @@ class ChannelData: #获取最后一帧图片 def get_last_frame(self): - with self.lock: - frame = self.last_frame - return frame - # if not self.frame_queue.empty(): - # return self.frame_queue.get() - # else: - # return None - + if self.b_model: + # with self.lock: + # frame = self.last_frame + # return frame + + #if not self.frame_queue.empty(): + try: + frame = self.frame_queue.get(timeout=0.3) #web传输没有做帧率控制了,可以超时时间长一点 + except queue.Empty: + print("channel--frame None") + return None + # else: + # return None + return frame + else: #如果没有运行,直接从cap获取画面 + if self.cap: + ret, frame = self.cap.read() # 除了第一帧,其它应该都是有画面的 + if not ret: + print("channel--frame None") + return None + ret, frame_bgr_webp = cv2.imencode('.jpg', frame) + if not ret: + buffer_bgr_webp = None + else: + buffer_bgr_webp = frame_bgr_webp.tobytes() + return buffer_bgr_webp + return None def update_last_frame(self,buffer): if buffer: - with self.lock: - self.last_frame = None - self.last_frame = buffer - # if not self.frame_queue.full(): - # self.frame_queue.put(buffer) - # else: - # self.frame_queue.get() # 丢弃最旧的帧 - # self.frame_queue.put(buffer) - + # with self.lock: + # self.last_frame = None + # self.last_frame = buffer + + # if self.frame_queue.full(): + # try: + # print("channel--丢帧") + # self.frame_queue.get(timeout=0.01) + # except queue.Empty: #为空不处理 + # pass + # self.frame_queue.put(buffer) + + try: + self.frame_queue.put(buffer,timeout=0.05) + except queue.Full: + #print("channel--未插入") + pass #帧序列号自增 一个线程中处理,不用加锁 def increment_counter(self): @@ -58,13 +91,22 @@ class ChannelData: def get_counter(self): return self.counter - #清空数据,主要是删除deque 和 last_frame + #清空数据,停止工作线程(若有 ,并删除deque 和 last_frame) def clear(self): + start_time = time.time() with self.lock: - self.bool_run = False - time.sleep(1) #休眠一秒,等待通道对应的子线程,停止工作。 - self.deque_frame.clear() - self.last_frame = None + if self.b_model: #b_model为true,说明开启了工作线程 + self.bool_run = False + self.work_th.join() #等待通道对应的子线程,停止工作。 + #time.sleep(1) + self.deque_frame.clear() + self.last_frame = None #二选一 + self.frame_queue = queue.Queue(maxsize=1) #二选一 + self.counter = 0 + + end_time = time.time() + execution_time = end_time - start_time + print(f"停止一个通道线程,花费了: {execution_time} seconds") def stop_run(self): self.bool_run = False @@ -73,11 +115,11 @@ class ChannelData: class ChannelManager: def __init__(self): self.channels = {} - self.lock = threading.RLock() # 用于保证字典操作的线程安全 + self.cm_lock = threading.RLock() # 用于保证字典操作的线程安全 #增加节点 def add_channel(self, channel_id, str_url, int_type, bool_run, deque_length=10,icount_max=100000): - with self.lock: + with self.cm_lock: if channel_id in self.channels: #若已经有数据,先删除后再增加 self.channels[channel_id].clear() # 手动清理资源 del self.channels[channel_id] @@ -86,29 +128,33 @@ class ChannelManager: return ch_data #删除节点 - def delete_channel(self, channel_id): - with self.lock: + def delete_channel(self, channel_id): #需要验证资源的释放清空 + with self.cm_lock: if channel_id in self.channels: self.channels[channel_id].clear() # 手动清理资源 + self.channels[channel_id].cap.release() del self.channels[channel_id] #获取节点 def get_channel(self, channel_id): - with self.lock: + with self.cm_lock: return self.channels.get(channel_id) #停止工作线程---要把视频采集线程停止掉 def stop_channel(self,channel_id): - with self.lock: + with self.cm_lock: if channel_id == 0: - for clannel_id,clannel_data in self.channels.items(): - clannel_data.cap.running = False - clannel_data.clear() #clear 里面已经停止了通道的工作线程 - del self.channels + # for clannel_id,clannel_data in self.channels.items(): + # clannel_data.clear() + for clannel_data in self.channels: + clannel_data.clear() #停止工作线程,并清空业务数据 + clannel_data.cap.release() #停止视频采集线程,并是否采集资源 + + self.channels.clear() #清空整个字典 else: if channel_id in self.channels: - self.channels[channel_id].cap.running = False self.channels[channel_id].clear() # 手动清理资源 + self.channels[channel_id].cap.release() del self.channels[channel_id] if __name__ == "__main__": diff --git a/core/DBManager.py b/core/DBManager.py index 0418c4c..eaf2f86 100644 --- a/core/DBManager.py +++ b/core/DBManager.py @@ -108,31 +108,31 @@ class DBManager(): ''' #根据通道ID或者模型ID删除通道和模型间的关联数据 1-通道ID,2-模型ID ,注意会有删除没有数据的情况 :param ID: - :param itype: - :return: + :param itype:1-通道ID,2-模型ID + :return: 删除数据库记录没做特别的判断 ''' #channel2model + col_name = "" if itype ==1: - strsql = f"select ID from channel2model where channel_id={ID};" - datas = self.do_select(strsql) - - strsql = f"delete from channel2model where channel_id={ID};" - ret = self.do_sql(strsql) + col_name = "channel_id" elif itype ==2: - strsql = f"select ID from channel2model where model_id={ID};" - datas = self.do_select(strsql) - - strsql = f"delete from channel2model where model_id={ID};" - ret = self.do_sql(strsql) + col_name = "model_id" else: - return False - #schedule - for data in datas: + return False + + strsql = f"select ID from channel2model where {col_name}={ID};" + data = self.do_select(strsql,1) + if data: c2m_id = data[0] + strsql = f"delete from channel2model where {col_name}={ID};" + ret = self.do_sql(strsql) + # schedule --- 调整后一个通道就一个mode strsql = f"delete from schedule where channel2model_id={c2m_id};" ret = self.do_sql(strsql) + return True + #删除通道,需要关联删除布防时间,通道和算法的关联表 def delchannel(self,ID): ret = self.delC2M(ID,1) @@ -148,51 +148,32 @@ class DBManager(): #修改视频通道和算法间的关联关系 #channel_id 通道ID #modell_list 最新配置的模型id list - def updateC2M(self,channel_id,model_list): - strsql = f"select model_id from channel2model where channel_id={channel_id};" - datas = set(self.do_select(strsql)) - data_new = set(model_list) - #计算要新增和修改的 - need_add = data_new - datas - need_del = datas-data_new - #新增 - for one in need_add: - strsql = f"insert into channel2model (channel_id,model_id) values ({channel_id},{one});" - if self.do_sql(strsql) == False: - return False - #初始化布防时间 -- 全1 - strsql = f"select ID from channel2model where channel_id={channel_id} and model_id={one};" - data = mDBM.do_select(strsql,1) - schedule_data_str = ("{'6': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " - "'0': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " - "'1': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " - "'2': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " - "'3': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]," - "'4': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]," - "'5': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}") - schedule_data = json.loads(schedule_data_str.replace("'", '"')) - for day, hours in schedule_data.items(): - for hour, status in enumerate(hours): - strsql = ( - f"insert into schedule (channel2model_id,day,hour,status) values ({ID},'{day}',{hour},{status})" - f" on conflict(channel2model_id,day,hour) do update set status=excluded.status;") - ret = mDBM.do_sql(strsql) - if not ret: - return ret - - #差删除 - for one in need_del: - strsql = f"select ID from channel2model where channel_id={channel_id} and model_id={one};" - c2m_id = mDBM.do_select(strsql,1)[0] - #删除布防计划数据 - strsql = f"delete from schedule where channel2model_id={c2m_id};" - if self.do_sql(strsql) == False: - return False - #删除关联记录 - strsql = f"delete from channel2model where ID = {c2m_id};" - if self.do_sql(strsql) == False: - return False - return True + def updateC2M(self,channel_id,model_id,check_area,polygon_str,conf_thres,iou_thres): + c2m_id = 0 + strsql = f"select ID from channel2model where channel_id={channel_id};" + data = self.do_select(strsql,1) + if data: #修改数据 + strsql = (f"update channel2model set model_id = {model_id},check_area={check_area}," + f"polygon='{polygon_str}',conf_thres={conf_thres},iou_thres={iou_thres} " + f"where channel_id={channel_id};") + else: #插入数据 + strsql = (f"insert into channel2model (channel_id,model_id,check_area,polygon,conf_thres,iou_thres) " + f"values ({channel_id},{model_id},{check_area},'{polygon_str}',{conf_thres},{iou_thres});") + ret = self.do_sql(strsql) + if not ret: + return c2m_id + else: + if data: + return data[0] + else: + strsql = f"select ID from channel2model where channel_id={channel_id};" + data = self.do_select(strsql,1) + if data: + return data[0] + else: + print("正常不会没有值!!") + return 0 + #检查设备ID是否在数据库? def checkDevID(self,cID): diff --git a/core/ModelManager.py b/core/ModelManager.py index fc814c1..3399e74 100644 --- a/core/ModelManager.py +++ b/core/ModelManager.py @@ -1,16 +1,11 @@ # 导入代码依赖 import time -import av import os import cv2 -import numpy as np import threading import importlib.util import datetime -import math -import copy -import queue -from collections import deque + from core.DBManager import mDBM,DBManager from myutils.MyLogger_logger import LogHandler from myutils.ConfigManager import myCongif @@ -18,95 +13,7 @@ from model.plugins.ModelBase import ModelBase from core.ChannelManager import ChannelManager from core.ACLModelManager import ACLModeManger from core.WarnManager import WarnManager,WarnData - -from PIL import Image - - -class VideoCaptureWithFPS: - '''视频捕获的封装类,是一个通道一个''' - def __init__(self, source): - self.source = source - self.width = None - self.height = None - # GStreamer - #rtsp_stream = f"rtspsrc location={self.source} ! decodebin ! videoconvert ! appsink" - pipeline = ( - f"rtspsrc location={self.source} latency=0 ! " - "rtph264depay ! " - "h264parse ! " - "avdec_h264 ! " # 使用 avdec_h264 代替其他解码器 - "videoscale ! " - "video/x-raw,width=640,height=480,framerate=10/1 ! " # 降低分辨率和帧率 - "videoconvert ! " - "appsink" - ) - self.cap = cv2.VideoCapture(pipeline, cv2.CAP_GSTREAMER) - # opencv - # self.cap = cv2.VideoCapture(self.source) - if self.cap.isOpened(): #若没有打开成功,在读取画面的时候,已有判断和处理 -- 这里也要检查下内存的释放情况 - self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - print(self.width,self.height) - #self.fps = fps # 线程保持最大帧率的刷新画面---过高的帧率会影响CPU性能,但过地的帧率会造成帧积压 - self.fps = math.ceil(self.cap.get(cv2.CAP_PROP_FPS)/float(myCongif.get_data("verify_rate"))) #向上取整。 - #print(self.fps) - self.running = True - #self.frame_queue = queue.Queue(maxsize=1) - self.frame = None - self.read_lock = threading.Lock() - self.thread = threading.Thread(target=self.update) - self.thread.start() - - def update(self): - icount = 0 - while self.running: - ret, frame = self.cap.read() - if not ret: - icount += 1 - if icount > 5: #重连 - self.cap.release() - self.cap = cv2.VideoCapture(self.source) - if self.cap.isOpened(): - self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - print(self.width,self.height) - # self.fps = fps # 线程保持最大帧率的刷新画面---过高的帧率会影响CPU性能,但过地的帧率会造成帧积压 - self.fps = math.ceil( - self.cap.get(cv2.CAP_PROP_FPS) / float(myCongif.get_data("verify_rate"))) # 向上取整。 - icount = 0 - else: - sleep_time = myCongif.get_data("cap_sleep_time") - print(f"{self.source}视频流,将于{sleep_time}秒后重连!") - time.sleep(sleep_time) - continue - #resized_frame = cv2.resize(frame, (int(self.width / 2), int(self.height / 2))) - with self.read_lock: - self.frame = frame - # if not self.frame_queue.full(): - # self.frame_queue.put(resized_frame) - - # 跳过指定数量的帧以避免积压 - for _ in range(self.fps): - self.cap.grab() - # time.sleep(self.fps) #按照视频源的帧率进行休眠 - #print("Frame updated at:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) - - def read(self): - with self.read_lock: - frame = self.frame.copy() if self.frame is not None else None - if frame is not None: - return True, frame - else: - return False, None - # if not self.frame_queue.empty(): - # return True, self.frame_queue.get() - # else: - # return False, None - - def release(self): - self.running = False - self.thread.join() - self.cap.release() +from core.CapManager import VideoCaptureWithFPS class ModelManager: def __init__(self): @@ -147,12 +54,13 @@ class ModelManager: raise Exception("视频参数错误!") return cap - def _import_model(self,model_name,model_path,threshold): + def _import_model(self,model_name,model_path,threshold,iou_thres): ''' 根据路径,动态导入模块 :param model_name: 模块名称 :param model_path: 模块路径 :param threshold: 置信阈值 + :param iou_thres: iou阈值 :return: ''' if os.path.exists(model_path): @@ -162,28 +70,24 @@ class ModelManager: return None module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) - md = getattr(module, "Model")(model_path,threshold) #实例化类 + md = getattr(module, "Model")(model_path,threshold,iou_thres) #实例化类 if not isinstance(md, ModelBase): self.logger.error("{} not zf_model".format(md)) return None - if md.init_ok == False: - self.logger.error("离线模型加载初始化失败!") - return None - else: self.logger.error("{}文件不存在".format(model_path)) return None self.logger.debug(f"{model_path} 加载成功!!!!") return md - def getschedule(self,c2m_id,myDBM): + def getschedule(self,c2m_id): ''' 根据c2mID 查询该算法的布防时间 :param c2m_id: :return: 以day为行,hour作为列的,布防标识值二维list ''' strsql = f"select day,hour,status from schedule where channel2model_id ={c2m_id} order by hour asc,day asc;" - datas = myDBM.do_select(strsql) + datas = mDBM.do_select(strsql) onelist = [] twolist = [] threelist = [] @@ -231,8 +135,7 @@ class ModelManager: weekday = now.weekday() # 获取星期几,星期一是0,星期天是6 hour = now.hour result.pop(0) # 保障结果数组定长 --先把最早的结果推出数组 - detections = None - bwarn = False + warntext = "" if model and schedule[weekday][hour] == 1: #不在计划则不进行验证,直接返回图片 # 调用模型,进行检测,model是动态加载的,具体的判断标准由模型内执行 ---- ********* @@ -265,41 +168,29 @@ class ModelManager: buffer_bgr_webp = frame_bgr_webp.tobytes() return buffer_bgr_webp,img,warntext - def dowork_thread(self,channel_id): + def dowork_thread(self,channel_id,model_data,schedule,m,verify_rate,warn_interval): '''一个通道一个线程,关联的模型在一个线程检测,局部变量都是一个通道独有''' channel_data = self.verify_list.get_channel(channel_id) #是对ChannelData 对象的引用 context = None # 线程ACL初始化 if self.model_platform == "acl": # ACL线程中初始化内容 context = ACLModeManger.th_inti_acl(self.device_id) - #查询关联的模型 --- 在循环运行前把基础数据都准备好 - myDBM = DBManager() - myDBM.connect() - strsql = (f"select t1.model_id,t1.check_area,t1.polygon ,t2.duration_time,t2.proportion,t2.model_path,t1.ID," - f"t2.model_name,t1.conf_threshold " - f"from channel2model t1 left join model t2 on t1.model_id = t2.ID where t1.channel_id ={channel_id};") - #print(strsql) - model = myDBM.do_select(strsql,1) #2024-7-12调整规则,一个通道只关联一个模型,表结构暂时不动 - if len(model) ==0: - print(f"{channel_id}视频通道没有关联模型,结束线程!") - return - - #基于基类实例化模块类 - m = self._import_model("",model[5],model[8]) #动态加载模型处理文件py - schedule = self.getschedule(model[6], myDBM) - result = [0 for _ in range(model[3] * myCongif.get_data("verify_rate"))] # 初始化时间*验证帧率数量的结果list + #初始化模型资源 + ret = m.init_acl_resource() + if not ret: + print("初始化模型资源出错,退出线程!") + return + channel_data.b_model = True + result = [0 for _ in range(model_data[3] * verify_rate)] # 初始化时间*验证帧率数量的结果list + proportion = model_data[4] # 判断是否报警的占比 #model[6] -- c2m_id --布防计划 0-周一,6-周日 warn_last_time = time.time() - proportion = model[4] #判断是否报警的占比 warn_save_count = 0 #保存录像的最新帧初始化为0 #开始拉取画面循环检测 cap = channel_data.cap last_frame_time = time.time() #初始化个读帧时间 - #可以释放数据库资源 - del myDBM - warn_interval = myCongif.get_data("warn_interval") while channel_data.bool_run: #基于tag 作为运行标识。 线程里只是读,住线程更新,最多晚一轮,应该不用线程锁。需验证 # 帧率控制帧率 current_time = time.time() @@ -312,7 +203,7 @@ class ModelManager: if not ret: continue #没读到画面继续 #执行图片推理 - buffer_bgr_webp,img_bgr_ndarray,warn_text = self.verify(frame,m,model,channel_id,schedule,result) + buffer_bgr_webp,img_bgr_ndarray,warn_text = self.verify(frame,m,model_data,channel_id,schedule,result) #分析图片放入内存中 channel_data.add_deque(img_bgr_ndarray) # 缓冲区大小由maxlen控制 超上限后,删除最前的数据 #channel_data.increment_counter() #帧序列加一 @@ -333,7 +224,7 @@ class ModelManager: warn_last_time = current_time # 处理报警 warn_data = WarnData() - warn_data.model_name = model[7] + warn_data.model_name = model_data[7] warn_data.warn_text = warn_text warn_data.img_buffer = channel_data.copy_deque() # 深度复制缓冲区 warn_data.width = cap.width @@ -353,14 +244,23 @@ class ModelManager: # cv2.imshow(str(channel_id), img) # if cv2.waitKey(1) & 0xFF == ord('q'): # break + #结束线程 - cap.release() #视频采集线程结束 - if context:#ACL线程中反初始化内容 -- 若线程异常退出,这些资源就不能正常释放了 - #先释放每个模型资源 - del model - #再释放context - ACLModeManger.th_del_acl(context) + print("开始结束工作线程") + channel_data.b_model = False + if self.model_platform == "acl": # ACL线程中初始化内容 + try: + m.release() #释放模型资源资源 + #释放context + if context: # ACL线程中反初始化内容 -- 若线程异常退出,这些资源就不能正常释放了 + # 再释放context + ACLModeManger.th_del_acl(context) + except Exception as e: + print(e) + #删除模型对象 + del m #cv2.destroyAllWindows() + print("线程结束!!!!") def send_warn(self): '''发送报警信息''' @@ -379,60 +279,79 @@ class ModelManager: strsql = "select id,ulr,type from channel where is_work = 1;" #执行所有通道 else: strsql = f"select id,ulr,type from channel where is_work = 1 and id = {channel_id};" #单通道启动检测线程 + datas = mDBM.do_select(strsql) for data in datas: - # channel_id, str_url, int_type, bool_run, deque_length - c_data = self.verify_list.add_channel(data[0],data[1],data[2],True, + channel_id = data[0] + #1.创建channel对象 channel_id, str_url, int_type, bool_run, deque_length + c_data = self.verify_list.add_channel(channel_id,data[1],data[2],True, myCongif.get_data("buffer_len"),myCongif.get_data("RESET_INTERVAL")) - # 启动该通道的视频捕获线程 --把视频捕获线程,放主线程创建 + #2.启动该通道的视频捕获线程 --把视频捕获线程,放主线程创建 c_data.cap = self._open_view(c_data.str_url, c_data.int_type) # 创建子线程读画面-把cap给模型就行-- - th_chn = threading.Thread(target=self.dowork_thread, args=(data[0],)) #一个视频通道一个线程,线程句柄暂时部保留 - th_chn.start() + #3.启动工作线程 ************************** + self.start_work_th(channel_id,c_data) + + # 启动告警线程 if self.warnM is None: self.warnM = WarnManager() self.warnM.start_warnmanager_th() - def stop_work(self,channel_id=0): - '''停止工作线程,0-停止所有,非0停止对应通道ID的线程''' - self.verify_list.stop_channel(channel_id) + def stop_work(self,channel_id=0): #要对应start_work 1.停止工作线程,2.停止cap线程。3.删除c_data + '''停止工作线程(包括采集线程,并删除通道数据对象),0-停止所有,非0停止对应通道ID的线程''' + try: + self.verify_list.stop_channel(channel_id) + except Exception as e: + print(e) + if channel_id == 0: #停止告警线程 self.warnM.brun = False + + def start_work_th(self,channel_id,c_data): + verify_rate = myCongif.get_data("verify_rate") + warn_interval = myCongif.get_data("warn_interval") + + strsql = ( + f"select t1.model_id,t1.check_area,t1.polygon ,t2.duration_time,t2.proportion,t2.model_path,t1.ID," + f"t2.model_name,t1.conf_thres,t1.iou_thres " + f"from channel2model t1 left join model t2 on t1.model_id = t2.ID where t1.channel_id ={channel_id};") + model_data = mDBM.do_select(strsql, 1) # 2024-7-12调整规则,一个通道只关联一个模型,表结构暂时不动 + if model_data and model_data[0]: # 如果该通道关联了模型 + # 基于基类实例化模块类 + m = self._import_model("", model_data[5], model_data[8], model_data[9]) # 动态加载模型处理文件py + if m: + schedule = self.getschedule(model_data[6]) # 获取布防计划 + # 数据准备OK-开始工作线程 + c_data.bool_run = True + c_data.work_th = threading.Thread(target=self.dowork_thread, + args=(channel_id, model_data, schedule, m, verify_rate, + warn_interval)) # 一个视频通道一个线程 + c_data.work_th.start() + + def restartC2M(self,channel_id): ''' 修改通道管理的算法模型后需要对该通道算法执行部分重新加载执行 :param channel_id: :return: ''' - pass + channel_data = self.verify_list.get_channel(channel_id) + #停止该通道的工作线程 --dowork_thread -- 并清空channel_data中的业务数据 + channel_data.clear() + + #重启该通道的工作线程 + self.start_work_th(channel_id,channel_data) + #print(f"Current working directory (ModelManager.py): {os.getcwd()}") mMM = ModelManager() def test1(): - - print(cv2.getBuildInformation()) - source = 'rtsp://192.168.3.44/live1' - gstreamer_pipeline = ( - f"rtspsrc location={source} protocols=udp latency=0 ! " - "rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! appsink" - ) - cap = cv2.VideoCapture(gstreamer_pipeline, cv2.CAP_GSTREAMER) - if not cap.isOpened(): - print("Error: Unable to open the video source.") - return - else: - print("Successfully opened the video source.") - ret, frame = cap.read() - if ret: - cv2.imshow('Frame', frame) - cv2.waitKey(0) - cap.release() - cv2.destroyAllWindows() + pass if __name__ == "__main__": diff --git a/core/Upload_file.py b/core/Upload_file.py index e7593af..fec9919 100644 --- a/core/Upload_file.py +++ b/core/Upload_file.py @@ -1,15 +1,129 @@ -from quart import Blueprint, render_template, request, redirect, url_for, flash, current_app import os import subprocess -from werkzeug.utils import secure_filename +import platform +import zipfile +import importlib.util +import shutil from myutils.ConfigManager import myCongif +from model.plugins.ModelBase import ModelBase def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in myCongif.get_data('ALLOWED_EXTENSIONS') #对上传的系统升级包进行检查 type:1--系统升级包,2--算法升级包 -def check_file(filepath,type): - pass +def check_file(filepath,filename_pre,type): #默认路径一般都是uploads/文件名 + ''' + 检查上传文件的合法性,若符合要求则移动到正式路径下面 + :param filepath: .zip文件路径 + :param filename_pre: 去除掉.zip的纯文件名 + :param type: 1--系统升级包, 2--算法升级包 + :return: model_version model_name model_path(相对路径) + ''' + model_name = None + model_version = None + model_path = None + system = platform.system() + + #path = filepath.rsplit('.', 1)[0] #去掉后缀 + path = myCongif.get_data("UPLOAD_FOLDER") # uploads + zip_path = filepath.rsplit('.', 1)[0] # uploads/filenamedir + filepath_py = zip_path + '/' + filename_pre + '.py' #这里就需要约束py文件名,就是zip压缩包的文件名 + + buzip = False + #解压缩 + if system == "Windows": + try: + with zipfile.ZipFile(filepath, 'r') as zip_ref: + zip_ref.extractall(path) + buzip = True + except zipfile.BadZipfile: + print("文件格式错误,解压失败") + except Exception as e: + print(f"解压失败: {e}") + elif system == "Linux": + try: + subprocess.run(['unzip', '-o', filepath, '-d', path], check=True) + buzip = True + except subprocess.CalledProcessError as e: + print(f"解压失败: {e.stderr}") + except Exception as e: + print(f"解压失败: {e}") + else: + raise NotImplementedError(f"Unsupported operating system: {system}") + #加载模型文件,获取模型名称和版本号 + if buzip: + if type == 2: #模型升级包 + print(filepath_py) + model = import_model("",filepath_py,0) + if model: + #把解压文件移动至正式路径 + tag_path = myCongif.get_data("Model_Plugins") #model/plugins + ret = move_dir(zip_path,tag_path,filename_pre) + if ret: + model_name = model.name #算法名 + model_version = model.version #算法版本 + model_path = tag_path+'/'+ filename_pre +'/'+filename_pre +'.py' #py文件的路径,是相对路径 + del model + elif type == 1: #系统升级包 + pass + else: + pass #错误值 + return model_version,model_name,model_path + +def move_dir(source_path,tag_path,filename_pre,type=1): + ''' + 移动文件夹 + :param source_path: 源文件夹 ***/***/filedir + :param tag_path: 目标路径 ***/***/ 不需要带filedir + :param filename_pre: 不带后缀的文件名 + :param type: 0-不覆盖移动,目标路径存在filedir的话返回, 1-覆盖移动,删除后再移动 + :return: False True + ''' + bsuccess = False + #若根目录不在,则创建 + if not os.path.exists(tag_path): #model/plugins + os.makedirs(tag_path) + #判断移动后目录是否存在 + newpath = tag_path + '/' + filename_pre + if os.path.exists(newpath): + if type == 1: + shutil.rmtree(newpath) + else: + return bsuccess #这个返回失败 + + # 移动文件夹 + try: + shutil.move(source_path, tag_path) + print(f"成功将文件夹移动到 {tag_path}") + bsuccess = True + except Exception as e: + print(f"移动文件夹失败: {e}") + return bsuccess + +def import_model(model_name,model_path,threshold): + ''' + 根据路径,动态导入模块 + :param model_name: 模块名称 + :param model_path: 模块路径 + :param threshold: 置信阈值 + :return: + ''' + if os.path.exists(model_path): + module_spec = importlib.util.spec_from_file_location(model_name, model_path) + if module_spec is None: + print(f"{model_path} 加载错误") + return None + module = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(module) + md = getattr(module, "Model")(model_path,threshold) #实例化类 + if not isinstance(md, ModelBase): + print("{} not zf_model".format(md)) + return None + else: + print("{}文件不存在".format(model_path)) + return None + print(f"{model_path} 加载成功!!!!") + return md def update_system(filepath): #系统升级 pass diff --git a/model/ModelManager.py b/model/ModelManager.py deleted file mode 100644 index 06b2535..0000000 --- a/model/ModelManager.py +++ /dev/null @@ -1,204 +0,0 @@ -import torch -import cv2 -import numpy as np -import torch -import os -import importlib -from model.plugins.ModelBase import ModelBase -from loguru import logger - -''' -class ModelManager_tmp(): - def __init__(self): - print("ModelInit") - - def __del__(self): - print("ModelManager DEL") - - def __preprocess_image(self,image, cfg, bgr2rgb=True): - """图片预处理""" - img, scale_ratio, pad_size = letterbox(image, new_shape=cfg['input_shape']) - if bgr2rgb: - img = img[:, :, ::-1] - img = img.transpose(2, 0, 1) # HWC2CHW - img = np.ascontiguousarray(img, dtype=np.float32) - return img, scale_ratio, pad_size - - def __draw_bbox(self,bbox, img0, color, wt, names): - """在图片上画预测框""" - det_result_str = '' - for idx, class_id in enumerate(bbox[:, 5]): - if float(bbox[idx][4] < float(0.05)): - continue - img0 = cv2.rectangle(img0, (int(bbox[idx][0]), int(bbox[idx][1])), (int(bbox[idx][2]), int(bbox[idx][3])), - color, wt) - img0 = cv2.putText(img0, str(idx) + ' ' + names[int(class_id)], (int(bbox[idx][0]), int(bbox[idx][1] + 16)), - cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) - img0 = cv2.putText(img0, '{:.4f}'.format(bbox[idx][4]), (int(bbox[idx][0]), int(bbox[idx][1] + 32)), - cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) - det_result_str += '{} {} {} {} {} {}\n'.format( - names[bbox[idx][5]], str(bbox[idx][4]), bbox[idx][0], bbox[idx][1], bbox[idx][2], bbox[idx][3]) - return img0 - - def __get_labels_from_txt(self,path): - """从txt文件获取图片标签""" - labels_dict = dict() - with open(path) as f: - for cat_id, label in enumerate(f.readlines()): - labels_dict[cat_id] = label.strip() - return labels_dict - - def __draw_prediction(self,pred, image, labels): - """在图片上画出预测框并进行可视化展示""" - imgbox = widgets.Image(format='jpg', height=720, width=1280) - img_dw = self.__draw_bbox(pred, image, (0, 255, 0), 2, labels) - imgbox.value = cv2.imencode('.jpg', img_dw)[1].tobytes() - display(imgbox) - - def __infer_image(self,img_path, model, class_names, cfg): - """图片推理""" - # 图片载入 - image = cv2.imread(img_path) - # 数据预处理 - img, scale_ratio, pad_size = self.__preprocess_image(image, cfg) - # 模型推理 - output = model.infer([img])[0] - - output = torch.tensor(output) - # 非极大值抑制后处理 - boxout = nms(output, conf_thres=cfg["conf_thres"], iou_thres=cfg["iou_thres"]) - pred_all = boxout[0].numpy() - # 预测坐标转换 - scale_coords(cfg['input_shape'], pred_all[:, :4], image.shape, ratio_pad=(scale_ratio, pad_size)) - # 图片预测结果可视化 - self.__draw_prediction(pred_all, image, class_names) - - def __infer_frame_with_vis(self,image, model, labels_dict, cfg, bgr2rgb=True): - # 数据预处理 - img, scale_ratio, pad_size = self.__preprocess_image(image, cfg, bgr2rgb) - # 模型推理 - output = model.infer([img])[0] - - output = torch.tensor(output) - # 非极大值抑制后处理 - boxout = nms(output, conf_thres=cfg["conf_thres"], iou_thres=cfg["iou_thres"]) - pred_all = boxout[0].numpy() - # 预测坐标转换 - scale_coords(cfg['input_shape'], pred_all[:, :4], image.shape, ratio_pad=(scale_ratio, pad_size)) - # 图片预测结果可视化 - img_vis = self.__draw_bbox(pred_all, image, (0, 255, 0), 2, labels_dict) - return img_vis - - def __img2bytes(self,image): - """将图片转换为字节码""" - return bytes(cv2.imencode('.jpg', image)[1]) - def __infer_camera(self,model, labels_dict, cfg): - """外设摄像头实时推理""" - - def find_camera_index(): - max_index_to_check = 10 # Maximum index to check for camera - - for index in range(max_index_to_check): - cap = cv2.VideoCapture(index) - if cap.read()[0]: - cap.release() - return index - - # If no camera is found - raise ValueError("No camera found.") - - # 获取摄像头 --这里可以换成RTSP流 - camera_index = find_camera_index() - cap = cv2.VideoCapture(camera_index) - # 初始化可视化对象 - image_widget = widgets.Image(format='jpeg', width=1280, height=720) - display(image_widget) - while True: - # 对摄像头每一帧进行推理和可视化 - _, img_frame = cap.read() - image_pred = self.__infer_frame_with_vis(img_frame, model, labels_dict, cfg) - image_widget.value = self.__img2bytes(image_pred) - - def __infer_video(self,video_path, model, labels_dict, cfg): - """视频推理""" - image_widget = widgets.Image(format='jpeg', width=800, height=600) - display(image_widget) - - # 读入视频 - cap = cv2.VideoCapture(video_path) - while True: - ret, img_frame = cap.read() - if not ret: - break - # 对视频帧进行推理 - image_pred = self.__infer_frame_with_vis(img_frame, model, labels_dict, cfg, bgr2rgb=True) - image_widget.value = self.__img2bytes(image_pred) - - def startWork(self,infer_mode,file_paht = ""): - cfg = { - 'conf_thres': 0.4, # 模型置信度阈值,阈值越低,得到的预测框越多 - 'iou_thres': 0.5, # IOU阈值,高于这个阈值的重叠预测框会被过滤掉 - 'input_shape': [640, 640], # 模型输入尺寸 - } - - model_path = 'yolo.om' - label_path = './coco_names.txt' - # 初始化推理模型 - model = InferSession(0, model_path) - labels_dict = self.__get_labels_from_txt(label_path) - - #执行验证 - if infer_mode == 'image': - img_path = 'world_cup.jpg' - self.__infer_image(img_path, model, labels_dict, cfg) - elif infer_mode == 'camera': - self.__infer_camera(model, labels_dict, cfg) - elif infer_mode == 'video': - video_path = 'racing.mp4' - self.__infer_video(video_path, model, labels_dict, cfg) -''' - -''' -算法实现类,实现算法执行线程,根据配内容,以线程方式执行算法模块 -''' -class ModelManager(): - def __init__(self): - print("ModelManager init") - - def __del__(self): - print("ModelManager del") - - def doWork(self): - pass - -#动态导入文件 -- 方法二 -- 相对推荐使用该方法 但spec感觉没什么用 -def import_source(spec, plgpath): - module = None - if os.path.exists(plgpath): - module_spec = importlib.util.spec_from_file_location(spec, plgpath) - module = importlib.util.module_from_spec(module_spec) - module_spec.loader.exec_module(module) - else: - logger.error("{}文件不存在".format(plgpath)) - return module - -#plgpath 为list [poc][file_name][name] -def run_plugin(plgpath, target,copy_flag=True): - module = import_source("", plgpath) - if module: - classname = "Model" - plg = getattr(module, classname)() - if not isinstance(plg, ModelBase): - raise Exception("{} not rx_Model".format(plg)) - new_plg = plg - result = new_plg.doWork("","","","") # 执行plugin基类的run, 返回结果 - return result - else: - print("模型加载失败") - return None - -def test(): - run_plugin("plugins/RYRQ_Model_ACL.py","") - -if __name__ == "__main__": - test() \ No newline at end of file diff --git a/model/plugins/AQM_Model.py b/model/plugins/AQM_Model.py deleted file mode 100644 index 79fd75b..0000000 --- a/model/plugins/AQM_Model.py +++ /dev/null @@ -1,9 +0,0 @@ -from model.plugins.ModelBase import ModelBase - -class Model(ModelBase): - def __init__(self): - super().__init__() - pass - - def doWork(self,image,mode,class_name,cfg,isdraw_box=False,bgr2rgb=True): - print("AQM_Model") \ No newline at end of file diff --git a/model/plugins/ModelBase.py b/model/plugins/ModelBase.py index e88da01..81ea57d 100644 --- a/model/plugins/ModelBase.py +++ b/model/plugins/ModelBase.py @@ -22,9 +22,19 @@ class ModelBase(ABC): :param threshold: 模型的置信阈值 ''' self.mylogger = LogHandler().get_logger("ModelManager") + self.platform = myCongif.get_data("model_platform") self.name = None #基于name来查询,用户对模型的配置参数,代表着模型名称需要唯一 2024-6-18 -逻辑还需要完善和验证 self.version = None self.model_type = None # 模型类型 1-图像分类,2-目标检测(yolov5),3-分割模型,4-关键点 + self.model_id = None # 模型 id + self.input_dataset = None # 输入数据结构 + self.output_dataset = None # 输出数据结构 + self.model_desc = None # 模型描述信息 + self._input_num = 0 # 输入数据个数 + self._output_num = 0 # 输出数据个数 + self._output_info = [] # 输出信息列表 + self._is_released = True # 资源是否被释放 + self.system = myCongif.get_data("model_platform") #platform.system() #获取系统平台 self.do_map = { # 定义插件的入口函数 -- # POCType.POC: self.do_verify, @@ -32,11 +42,21 @@ class ModelBase(ABC): # POCType.BRUTE: self.do_brute } self.model_path = path # 模型路径 - self.init_ok = False + #self.init_ok = False + #--------------------------- + #加载ACL模型文件---模型加载、模型执行、模型卸载的操作必须在同一个Context下 + # if self.platform == 'acl': + # if self.init_acl_resource(): # 加载离线模型,创建输出缓冲区 + # print("加载模型文件成功!") + # self.init_ok = True + # self._is_released = False # 资源是否被释放 + # else: #其他平台暂时不需要额外初始化内容 + # self.init_ok = True def __del__(self): - print("资源释放") + # 卸载ACL模型文件 + self.release() def draw_polygon(self, img, polygon_points,color=(0, 255, 0)): self.polygon = Polygon(ast.literal_eval(polygon_points)) @@ -59,16 +79,16 @@ class ModelBase(ABC): raise RuntimeError(ret) print('Init TH-Context Successfully') - def _del_acl(self): - device_id = 0 - # 线程释放context - ret = acl.rt.destroy_context(self.context) # 释放 Context - if ret: - raise RuntimeError(ret) - print('Deinit TH-Context Successfully') - print('ACL finalize Successfully') + # def _del_acl(self): + # device_id = 0 + # # 线程释放context + # ret = acl.rt.destroy_context(self.context) # 释放 Context + # if ret: + # raise RuntimeError(ret) + # print('Deinit TH-Context Successfully') + # print('ACL finalize Successfully') - def _init_resource(self): + def init_acl_resource(self): #self._init_acl() #测试使用 ''' 初始化模型、输出相关资源。相关数据类型: aclmdlDesc aclDataBuffer aclmdlDataset''' print("Init model resource") @@ -79,6 +99,8 @@ class ModelBase(ABC): print(f"{self.model_path}---模型加载失败!") return False self.model_desc = acl.mdl.create_desc() # 初始化模型信息对象 + if not self.model_desc: + return False ret = acl.mdl.get_desc(self.model_desc, self.model_id) # 根据模型ID获取该模型的aclmdlDesc类型数据(描述信息) print("[Model] Model init resource stage success") # 创建模型输出 dataset 结构 @@ -86,6 +108,7 @@ class ModelBase(ABC): if ret !=0: print("[Model] create model output dataset fail") return False + self._is_released = False # 资源是否被释放 return True def _gen_output_dataset(self): @@ -120,6 +143,7 @@ class ModelBase(ABC): if ret == FAILED: self._release_dataset(self.input_dataset) # 失败时释放dataset + self.input_dataset = None #print("[Model] create model input dataset success") def _unpack_bytes_array(self, byte_array, shape, datatype): @@ -176,9 +200,10 @@ class ModelBase(ABC): if ret: self.mylogger.error(f"acl.mdl.execute fail!--{ret}") self._release_dataset(self.input_dataset) # 失败时释放dataset --创建输入空间失败时会释放。 + self.input_dataset = None return None out_numpy = self._output_dataset_to_numpy() # 将推理输出的二进制数据流解码为numpy数组, 数组的shape和类型与模型输出规格一致 - self._release_dataset(self.input_dataset) # 释放dataset -- 要不要执行需要验证 + #self._release_dataset(self.input_dataset) # 释放dataset -- 要不要执行需要验证 return out_numpy def release(self): @@ -187,10 +212,12 @@ class ModelBase(ABC): return print("Model start release...") - self._release_dataset(self.input_dataset) # 释放输入数据结构 - self.input_dataset = None # 将输入数据置空 - self._release_dataset(self.output_dataset) # 释放输出数据结构 - self.output_dataset = None # 将输出数据置空 + if self.input_dataset: + self._release_dataset(self.input_dataset) # 释放输入数据结构 + self.input_dataset = None # 将输入数据置空 + if self.output_dataset: + self._release_dataset(self.output_dataset) # 释放输出数据结构 + self.output_dataset = None # 将输出数据置空 if self.model_id: ret = acl.mdl.unload(self.model_id) # 卸载模型 diff --git a/model/plugins/RYRQ/RYRQ_Model.py b/model/plugins/RYRQ/RYRQ_Model.py index edba0a6..5bf09ba 100644 --- a/model/plugins/RYRQ/RYRQ_Model.py +++ b/model/plugins/RYRQ/RYRQ_Model.py @@ -17,10 +17,10 @@ class Model(ModelBase): self.version = "V1.0" self.model_type = 2 - #实例化模型--实例化模型没有对失败的情况进行处理 - self.init_ok = True - self.model = torch.hub.load(yolov5_path, 'custom', path=model_file, source='local') - #if model 失败,inti_ok = Flase + # #实例化模型--实例化模型没有对失败的情况进行处理 + # self.init_ok = True + # self.model = torch.hub.load(yolov5_path, 'custom', path=model_file, source='local') + # #if model 失败,inti_ok = Flase def verify(self,image,data,isdraw=1): diff --git a/model/plugins/RYRQ_ACL/RYRQ_Model_ACL.py b/model/plugins/RYRQ_ACL/RYRQ_Model_ACL.py index 106d193..31f5fce 100644 --- a/model/plugins/RYRQ_ACL/RYRQ_Model_ACL.py +++ b/model/plugins/RYRQ_ACL/RYRQ_Model_ACL.py @@ -1,27 +1,18 @@ import os.path from model.plugins.ModelBase import ModelBase -from myutils.ConfigManager import myCongif from model.base_model.ascnedcl.det_utils import get_labels_from_txt, letterbox, scale_coords, nms, draw_bbox # 模型前后处理相关函数 import cv2 import numpy as np import torch # 深度学习运算框架,此处主要用来处理数据 -from core.ACLModelManager import ACLModeManger class Model(ModelBase): - def __init__(self,path,threshold=0.5): + def __init__(self,path,threshold=0.5,iou_thres=0.5): # 找pt模型路径 -- 一个约束py文件和模型文件的路径关系需要固定, -- 上传模型时,要解压好路径 dirpath, filename = os.path.split(path) self.model_file = os.path.join(dirpath, "yolov5s_bs1.om") # 目前约束模型文件和py文件在同一目录 self.coco_file = os.path.join(dirpath, "coco_names.txt") - super().__init__(self.model_file) #acl环境初始化基类负责类的实例化 - self.model_id = None # 模型 id - self.input_dataset = None # 输入数据结构 - self.output_dataset = None # 输出数据结构 - self.model_desc = None # 模型描述信息 - self._input_num = 0 # 输入数据个数 - self._output_num = 0 # 输出数据个数 - self._output_info = [] # 输出信息列表 - self._is_released = False # 资源是否被释放 + super().__init__(self.model_file) # acl环境初始化基类负责类的实例化 + self.name = "人员入侵-yolov5" self.version = "V1.0" self.model_type = 2 @@ -29,17 +20,7 @@ class Model(ModelBase): self.neth = 640 # 缩放的目标高度, 也即模型的输入高度 self.netw = 640 # 缩放的目标宽度, 也即模型的输入宽度 self.conf_threshold = threshold # 置信度阈值 - - #加载ACL模型文件---模型加载、模型执行、模型卸载的操作必须在同一个Context下 - if self._init_resource(): #加载离线模型,创建输出缓冲区 - print("加载模型文件成功!") - self.init_ok = True - - - def __del__(self): - #卸载ACL模型文件 - if self.init_ok: - self.release() + self.iou_thres = iou_thres # IOU阈值 def verify(self,image,data,isdraw=1): @@ -63,8 +44,9 @@ class Model(ModelBase): if outputs: output = outputs[0] #只放了一张图片 # 后处理 -- boxout 是 tensor-list: [tensor([[],[].[]])] --[x1,y1,x2,y2,置信度,coco_index] - boxout = nms(torch.tensor(output), conf_thres=0.3, - iou_thres=0.5) # 利用非极大值抑制处理模型输出,conf_thres 为置信度阈值,iou_thres 为iou阈值 + # 利用非极大值抑制处理模型输出,conf_thres 为置信度阈值,iou_thres 为iou阈值 + boxout = nms(torch.tensor(output), conf_thres=self.conf_threshold,iou_thres=self.iou_thres) + pred_all = boxout[0].numpy() # 转换为numpy数组 -- [[],[],[]] --[x1,y1,x2,y2,置信度,coco_index] # pred_all[:, :4] 取所有行的前4列,pred_all[:,1]--第一列 scale_coords([640, 640], pred_all[:, :4], image.shape, ratio_pad=(scale_ratio, pad_size)) # 将推理结果缩放到原始图片大小 diff --git a/model/plugins/yolov5-1.py b/model/plugins/yolov5-1.py deleted file mode 100644 index 76a9333..0000000 --- a/model/plugins/yolov5-1.py +++ /dev/null @@ -1,155 +0,0 @@ -# 导入代码依赖 -import cv2 -import numpy as np -from myutils.ConfigManager import myCongif -import os -import torch - -import ipywidgets as widgets -from IPython.display import display -from skvideo.io import vreader, FFmpegWriter -import IPython.display -from ais_bench.infer.interface import InferSession -from det_utils import letterbox, scale_coords, nms - -def preprocess_image(image, cfg, bgr2rgb=True): - """图片预处理""" - img, scale_ratio, pad_size = letterbox(image, new_shape=cfg['input_shape']) - if bgr2rgb: - img = img[:, :, ::-1] - img = img.transpose(2, 0, 1) # HWC2CHW - img = np.ascontiguousarray(img, dtype=np.float32) - return img, scale_ratio, pad_size - -def draw_bbox(bbox, img0, color, wt, names): - """在图片上画预测框""" - det_result_str = '' - for idx, class_id in enumerate(bbox[:, 5]): - if float(bbox[idx][4] < float(0.05)): - continue - img0 = cv2.rectangle(img0, (int(bbox[idx][0]), int(bbox[idx][1])), (int(bbox[idx][2]), int(bbox[idx][3])), - color, wt) - img0 = cv2.putText(img0, str(idx) + ' ' + names[int(class_id)], (int(bbox[idx][0]), int(bbox[idx][1] + 16)), - cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) - img0 = cv2.putText(img0, '{:.4f}'.format(bbox[idx][4]), (int(bbox[idx][0]), int(bbox[idx][1] + 32)), - cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) - det_result_str += '{} {} {} {} {} {}\n'.format( - names[bbox[idx][5]], str(bbox[idx][4]), bbox[idx][0], bbox[idx][1], bbox[idx][2], bbox[idx][3]) - return img0 - -def get_labels_from_txt(path): - """从txt文件获取图片标签""" - labels_dict = dict() - with open(path) as f: - for cat_id, label in enumerate(f.readlines()): - labels_dict[cat_id] = label.strip() - return labels_dict - -def draw_prediction(pred, image, labels): - """在图片上画出预测框并进行可视化展示""" - imgbox = widgets.Image(format='jpg', height=720, width=1280) - img_dw = draw_bbox(pred, image, (0, 255, 0), 2, labels) - imgbox.value = cv2.imencode('.jpg', img_dw)[1].tobytes() - display(imgbox) - -def infer_image(img_path, model, class_names, cfg): - """图片推理""" - # 图片载入 - image = cv2.imread(img_path) - # 数据预处理 - img, scale_ratio, pad_size = preprocess_image(image, cfg) - # 模型推理 - output = model.infer([img])[0] - - output = torch.tensor(output) - # 非极大值抑制后处理 - boxout = nms(output, conf_thres=cfg["conf_thres"], iou_thres=cfg["iou_thres"]) - pred_all = boxout[0].numpy() - # 预测坐标转换 - scale_coords(cfg['input_shape'], pred_all[:, :4], image.shape, ratio_pad=(scale_ratio, pad_size)) - # 图片预测结果可视化 - draw_prediction(pred_all, image, class_names) - -def infer_frame_with_vis(image, model, labels_dict, cfg, bgr2rgb=True): - # 数据预处理 - img, scale_ratio, pad_size = preprocess_image(image, cfg, bgr2rgb) - # 模型推理 - output = model.infer([img])[0] - - output = torch.tensor(output) - # 非极大值抑制后处理 - boxout = nms(output, conf_thres=cfg["conf_thres"], iou_thres=cfg["iou_thres"]) - pred_all = boxout[0].numpy() - # 预测坐标转换 - scale_coords(cfg['input_shape'], pred_all[:, :4], image.shape, ratio_pad=(scale_ratio, pad_size)) - # 图片预测结果可视化 - img_vis = draw_bbox(pred_all, image, (0, 255, 0), 2, labels_dict) - return img_vis - -def img2bytes(image): - """将图片转换为字节码""" - return bytes(cv2.imencode('.jpg', image)[1]) - -def infer_video(video_path, model, labels_dict, cfg): - """视频推理""" - image_widget = widgets.Image(format='jpeg', width=800, height=600) - display(image_widget) - - # 读入视频 - cap = cv2.VideoCapture(video_path) - while True: - ret, img_frame = cap.read() - if not ret: - break - # 对视频帧进行推理 - image_pred = infer_frame_with_vis(img_frame, model, labels_dict, cfg, bgr2rgb=True) - image_widget.value = img2bytes(image_pred) - -def infer_camera(model, labels_dict, cfg): - """外设摄像头实时推理""" - def find_camera_index(): - max_index_to_check = 10 # Maximum index to check for camera - - for index in range(max_index_to_check): - cap = cv2.VideoCapture(index) - if cap.read()[0]: - cap.release() - return index - - # If no camera is found - raise ValueError("No camera found.") - - # 获取摄像头 - camera_index = find_camera_index() - cap = cv2.VideoCapture(camera_index) - # 初始化可视化对象 - image_widget = widgets.Image(format='jpeg', width=1280, height=720) - display(image_widget) - while True: - # 对摄像头每一帧进行推理和可视化 - _, img_frame = cap.read() - image_pred = infer_frame_with_vis(img_frame, model, labels_dict, cfg) - image_widget.value = img2bytes(image_pred) - -if __name__ == "__main__": - cfg = { - 'conf_thres': 0.4, # 模型置信度阈值,阈值越低,得到的预测框越多 - 'iou_thres': 0.5, # IOU阈值,高于这个阈值的重叠预测框会被过滤掉 - 'input_shape': [640, 640], # 模型输入尺寸 - } - model_path = os.path.join(myCongif.get_data('weight_path'),'/yolov5-1/yolov5s.pt') - label_path = os.path.join(myCongif.get_data('weight_path'),'/yolov5-1/coco_names.txt') - # 初始化推理模型 - model = InferSession(0, model_path) - labels_dict = get_labels_from_txt(label_path) - - infer_mode = 'video' - - if infer_mode == 'image': - img_path = 'world_cup.jpg' - infer_image(img_path, model, labels_dict, cfg) - elif infer_mode == 'camera': - infer_camera(model, labels_dict, cfg) - elif infer_mode == 'video': - video_path = 'racing.mp4' - infer_video(video_path, model, labels_dict, cfg) \ No newline at end of file diff --git a/model/weights/yolov5-1/yoloV5.py b/model/weights/yolov5-1/yoloV5.py deleted file mode 100644 index c85e556..0000000 --- a/model/weights/yolov5-1/yoloV5.py +++ /dev/null @@ -1,64 +0,0 @@ -import torch -import cv2 -import numpy as np -from shapely.geometry import Point, Polygon -import os - -# # 自定义模型文件的路径 -# model_path = 'yolov5s.pt' # 假设模型文件名为 yolov5s.pt 并与执行文件在同一个目录 -# # 本地YOLOv5仓库路径 -# repo_path = '../base_model/yolov5' -# 自定义模型文件的路径 -print(f"Current working directory (yolov5.py): {os.getcwd()}") -model_path = 'D:/Project/FristProject/model/mode_test/yolov5s.pt' # 假设模型文件名为 yolov5s.pt 并与执行文件在同一个目录 -# 本地YOLOv5仓库路径 -repo_path = 'D:/Project/FristProject/model/base_model/yolov5' - -# 加载自定义模型 -model = torch.hub.load(repo_path, 'custom', path=model_path, source='local') - -# 定义监控区域(多边形顶点) -region_points = [(100, 100), (500, 100), (500, 400), (100, 400)] -polygon = Polygon(region_points) - -# 打开摄像头 -cap = cv2.VideoCapture(0) - -def is_point_in_polygon(point, polygon): - return polygon.contains(Point(point)) - -while True: - ret, frame = cap.read() - if not ret: - break - - # 进行推理 - results = model(frame) - detections = results.pandas().xyxy[0] - - # 绘制监控区域 - cv2.polylines(frame, [np.array(region_points, np.int32)], isClosed=True, color=(0, 255, 0), thickness=2) - - for _, row in detections.iterrows(): - if row['name'] == 'person': - # 获取人员检测框的中心点 - x_center = (row['xmin'] + row['xmax']) / 2 - y_center = (row['ymin'] + row['ymax']) / 2 - - if is_point_in_polygon((x_center, y_center), polygon): - # 触发报警 - cv2.putText(frame, 'Alert: Intrusion Detected', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) - print('Alert: Intrusion Detected') - - # 绘制检测框 - cv2.rectangle(frame, (int(row['xmin']), int(row['ymin'])), (int(row['xmax']), int(row['ymax'])), (255, 0, 0), 2) - cv2.circle(frame, (int(x_center), int(y_center)), 5, (0, 0, 255), -1) - - # 显示结果 - cv2.imshow('Frame', frame) - - if cv2.waitKey(1) & 0xFF == ord('q'): - break - -cap.release() -cv2.destroyAllWindows() diff --git a/myutils/IPManager.py b/myutils/IPManager.py new file mode 100644 index 0000000..d2e9274 --- /dev/null +++ b/myutils/IPManager.py @@ -0,0 +1,300 @@ +import subprocess +import platform +import locale +import re + +''' +针对windows和linux的网络信息获取和设置功能类。 +由于网络接口名字并不一定,又有多网卡等情况,实际应用时需要指定网络接口(固化硬件环境) +''' + +class IPManager: + def __init__(self): + self.os_type = platform.system() + self.encoding = locale.getpreferredencoding() + + def set_ip(self, interface_name, ip_address, subnet_mask, gateway): + if self.os_type == "Windows": + self._set_ip_windows(interface_name, ip_address, subnet_mask, gateway) + elif self.os_type == "Linux": + self._set_ip_linux(interface_name, ip_address, subnet_mask, gateway) + else: + raise NotImplementedError("Unsupported OS") + + def connect_wifi(self, ssid, password): + if self.os_type == "Windows": + self._connect_wifi_windows(ssid, password) + elif self.os_type == "Linux": + self._connect_wifi_linux(ssid, password) + else: + raise NotImplementedError("Unsupported OS") + + def get_wifi_list(self): + wifis = [] + if self.os_type == "Windows": + wifis = self._get_wifi_list_windows() + elif self.os_type == "Linux": + wifis = self._get_wifi_list_linux() + else: + raise NotImplementedError("Unsupported OS") + return wifis + + def get_connected_wifi(self): + ssid = None + if self.os_type == "Windows": + ssid = self._get_connected_wifi_windows() + elif self.os_type == "Linux": + ssid = self._get_connected_wifi_linux() + else: + raise NotImplementedError("Unsupported OS") + return ssid + + def get_network_info(self): + info = None + if self.os_type == "Windows": + info = self._get_network_info_windows() + elif self.os_type == "Linux": + info = self._get_network_info_linux() + else: + raise NotImplementedError("Unsupported OS") + return info + + def _set_ip_windows(self, interface_name, ip_address, subnet_mask, gateway): + command = f'netsh interface ip set address name="{interface_name}" static {ip_address} {subnet_mask} {gateway} 1' + #result = subprocess.run(command, shell=True,capture_output=True, text=True, encoding='utf-8') + # 打印输出结果 + result = self._run_cmd(command) + print(result.stdout) + + # 检查返回码 + if result.returncode == 0: + print("IP address set successfully.") + else: + print("Failed to set IP address. Please check the output for errors.") + + def _set_ip_linux(self, interface_name, ip_address, subnet_mask, gateway): + self._run_cmd(f"sudo ip addr flush dev {interface_name}") + self._run_cmd(f"sudo ip addr add {ip_address}/{subnet_mask} dev {interface_name}") + self._run_cmd(f"sudo ip route add default via {gateway}") + + def _connect_wifi_windows(self, ssid, password): + command = f'netsh wlan connect name="{ssid}"' + self._run_cmd(command) + + def _connect_wifi_linux(self, ssid, password): + command = f"nmcli dev wifi connect '{ssid}' password '{password}'" + self._run_cmd(command) + + def _get_wifi_list_windows(self): + command = "netsh wlan show networks" + result = self._run_cmd(command) + wifi_list = [] + lines = result.stdout.split('\n') + for line in lines: + if "SSID" in line and "BSSID" not in line: + ssid = line.split(":")[1].strip() + wifi_list.append(ssid) + + return wifi_list + + def _get_wifi_list_linux(self): + command = "nmcli dev wifi list" + result = self._run_cmd(command) + + # 解析输出结果 + wifi_list = [] + lines = result.stdout.split('\n') + for line in lines[1:]: # 跳过表头 + if line.strip(): + ssid = line.split()[0] + wifi_list.append(ssid) + + return wifi_list + + def _get_connected_wifi_windows(self): + command = "netsh wlan show interfaces" + result = self._run_cmd(command) + + # 使用正则表达式提取SSID + ssid_match = re.search(r"SSID\s+: (.+)", result.stdout) + + if ssid_match: + ssid = ssid_match.group(1).strip() + return ssid + else: + return None + + def _get_connected_wifi_linux(self): + command = "iwgetid -r" + result = self._run_cmd(command) + + ssid = result.stdout.strip() + if ssid: + return ssid + else: + return None + + def _get_network_info_windows(self): + command = "ipconfig /all" + result = self._run_cmd(command) + + interfaces = {} + current_interface = None + for line in result.stdout.splitlines(): + # 识别接口名称 + interface_match = re.match(r"^\s*([^:\s]+.*):$", line) + if interface_match: + current_interface = interface_match.group(1).strip() + interfaces[current_interface] = {"IP": None, "Subnet": None, "Gateway": None, "DNS": []} + + if current_interface: + # 解析IP地址 + ip_match = re.search(r"^\s*IPv4 地址[^\:]*:\s*(\d+\.\d+\.\d+\.\d+)", line) + if ip_match: + interfaces[current_interface]["IP"] = ip_match.group(1).strip() + + # 解析子网掩码 + subnet_match = re.search(r"^\s*子网掩码[^\:]*:\s*(\d+\.\d+\.\d+\.\d+)", line) + if subnet_match: + interfaces[current_interface]["Subnet"] = subnet_match.group(1).strip() + + # 解析网关 + gateway_match = re.search(r"^\s*默认网关[^\:]*:\s*(\d+\.\d+\.\d+\.\d+)", line) + if gateway_match: + interfaces[current_interface]["Gateway"] = gateway_match.group(1).strip() + + # 解析DNS服务器 + dns_match = re.search(r"^\s*DNS 服务器[^\:]*:\s*(\d+\.\d+\.\d+\.\d+)", line) + if dns_match: + interfaces[current_interface]["DNS"].append(dns_match.group(1).strip()) + else: + # 匹配后续行的DNS服务器 + dns_continued_match = re.search(r"^\s*(\d+\.\d+\.\d+\.\d+)", line) + if dns_continued_match: + interfaces[current_interface]["DNS"].append(dns_continued_match.group(1).strip()) + return interfaces + + def _get_network_info_linux(self): + # 获取IP地址、子网掩码和网关 + ip_info = self._run_cmd("ip addr show").stdout + route_info = self._run_cmd("ip route show").stdout + + # 获取DNS服务器 + dns_info = self._run_cmd("nmcli dev show | grep DNS").stdout + + interfaces = {} + current_interface = None + for line in ip_info.splitlines(): + # 识别接口名称 + interface_match = re.match(r"^\d+: ([^:\s]+):", line) + if interface_match: + current_interface = interface_match.group(1).strip() + interfaces[current_interface] = {"IP": None, "Subnet": None, "Gateway": None, "DNS": []} + + if current_interface: + # 解析IP地址和子网掩码 + ip_match = re.search(r"^\s*inet (\d+\.\d+\.\d+\.\d+)/(\d+)", line) + if ip_match: + interfaces[current_interface]["IP"] = ip_match.group(1).strip() + interfaces[current_interface]["Subnet"] = ip_match.group(2).strip() + + # 解析网关 + for line in route_info.splitlines(): + if "default via" in line: + gateway_match = re.search(r"default via (\d+\.\d+\.\d+\.\d+)", line) + interface_match = re.search(r"dev (\S+)", line) + if gateway_match and interface_match: + interface = interface_match.group(1).strip() + if interface in interfaces: + interfaces[interface]["Gateway"] = gateway_match.group(1).strip() + + # 解析DNS服务器 + for line in dns_info.splitlines(): + dns_match = re.search(r"DNS\[\d+\]:\s*(\d+\.\d+\.\d+\.\d+)", line) + if dns_match: + # 假设第一个接口是主要接口 + primary_interface = list(interfaces.keys())[0] + interfaces[primary_interface]["DNS"].append(dns_match.group(1).strip()) + + return interfaces + + def _get_interface_info_windows(self,interface_name): + command = f'netsh interface ip show config name="{interface_name}"' + result = self._run_cmd(command) + + info = {"IP": None, "Subnet": None, "Gateway": None, "DNS": []} + + # 解析IP地址 + ip_match = re.search(r"IP Address:\s*(\d+\.\d+\.\d+\.\d+)", result.stdout) + if ip_match: + info["IP"] = ip_match.group(1).strip() + + # 解析子网掩码 + subnet_match = re.search(r"Subnet Prefix:\s*(\d+\.\d+\.\d+\.\d+)", result.stdout) + if subnet_match: + info["Subnet"] = subnet_match.group(1).strip() + + # 解析网关 + gateway_match = re.search(r"Default Gateway:\s*(\d+\.\d+\.\d+\.\d+)", result.stdout) + if gateway_match: + info["Gateway"] = gateway_match.group(1).strip() + + # 解析DNS服务器 + dns_matches = re.findall(r"Statically Configured DNS Servers:\s*(\d+\.\d+\.\d+\.\d+)", result.stdout) + for dns in dns_matches: + info["DNS"].append(dns.strip()) + + return info + + def _get_interface_info_linux(self,interface_name): + info = {"IP": None, "Subnet": None, "Gateway": None, "DNS": []} + + # 获取IP地址和子网掩码 + ip_command = f"ip addr show dev {interface_name}" + ip_result = self._run_cmd(ip_command) + + ip_match = re.search(r"inet (\d+\.\d+\.\d+\.\d+)/(\d+)", ip_result.stdout) + if ip_match: + info["IP"] = ip_match.group(1).strip() + info["Subnet"] = ip_match.group(2).strip() + + # 获取网关信息 + gateway_command = f"ip route show dev {interface_name}" + gateway_result = subprocess.run(gateway_command, shell=True, capture_output=True, text=True, encoding='utf-8') + + gateway_match = re.search(r"default via (\d+\.\d+\.\d+\.\d+)", gateway_result.stdout) + if gateway_match: + info["Gateway"] = gateway_match.group(1).strip() + + # 获取DNS服务器信息 + dns_command = f"nmcli dev show {interface_name} | grep DNS" + dns_result = subprocess.run(dns_command, shell=True, capture_output=True, text=True, encoding='utf-8') + + dns_matches = re.findall(r"DNS\[\d+\]:\s*(\d+\.\d+\.\d+\.\d+)", dns_result.stdout) + for dns in dns_matches: + info["DNS"].append(dns.strip()) + + return info + + def _run_cmd(self,command): + ''' + 为了统一命令执行的返回参数格式,统一定义了一个执行函数 + :param command: + :return: + ''' + result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding=self.encoding) + return result + +IPM = IPManager() + +if __name__ == "__main__":#WLAN + # 示例用法 + nm = IPManager() + try: + #nm.set_ip("以太网 2", "192.168.1.100", "255.255.255.0", "192.168.1.1") + #nm.set_ip("WLAN", "192.168.3.100", "255.255.255.0", "192.168.3.1") #zhang wifi + network_info = nm.get_wifi_list() + print(network_info) + except Exception as e: + print(e) + #nm.connect_wifi("YourSSID", "YourPassword") diff --git a/run.py b/run.py index 97c7068..3af7222 100644 --- a/run.py +++ b/run.py @@ -7,6 +7,7 @@ import asyncio from hypercorn.asyncio import serve from hypercorn.config import Config from core.DBManager import mDBM +from core.Upload_file import allowed_file,check_file,updata_model print(f"Current working directory (run.py): {os.getcwd()}") web = create_app() @@ -16,16 +17,12 @@ async def run_quart_app(): await serve(web, config) def test(): - area_id = 1 - c_name = "55" - strsql = f"select ID from channel where area_id={area_id} and channel_name={c_name};" - data = mDBM.do_select(strsql, 1) - if data: - print("有值") - else: - print("无值") + filepath = "uploads/RYRQ_Model_ACL.zip" + check_file(filepath,2) if __name__ == '__main__': + #test() + system = platform.system() if system == "Windows": total, used, free = shutil.disk_usage("/") diff --git a/uploads/8.zip b/uploads/8.zip deleted file mode 100644 index 288d8ea..0000000 Binary files a/uploads/8.zip and /dev/null differ diff --git a/web/API/channel.py b/web/API/channel.py index ce14fed..00df48f 100644 --- a/web/API/channel.py +++ b/web/API/channel.py @@ -5,8 +5,10 @@ from web.common.utils import login_required from core.DBManager import mDBM from myutils.ReManager import mReM from core.ModelManager import mMM +from myutils.ConfigManager import myCongif import cv2 import base64 +import time @api.route('/channel/tree',methods=['GET']) @login_required @@ -48,19 +50,27 @@ async def channel_add(): #新增通道 -- 2024-8-1修改为与修改通道用一 reMsg = 'rtsp地址不合法' return jsonify({'status': reStatus, 'msg': reMsg}) strsql = f"select id from area where area_name = '{area}';" - ret = mDBM.do_select(strsql,1) - if ret: - strsql = f"select ID from channel where area_id={ret[0]} and channel_name={cName};" + area = mDBM.do_select(strsql,1) + if area: + area_id = area[0] + strsql = f"select ID from channel where area_id={area_id} and channel_name='{cName}';" data = mDBM.do_select(strsql, 1) - if data: #有值--代表重复了 + if data and data[0] != cid: #有值--代表重复 或者是它自己(只修改了RTSP地址) reStatus = 0 reMsg = "同一区域内的通道名称不能相同!" else: if cid == -1: + max_count = myCongif.get_data("max_channel_num") + strsql = "select count(*) from channel;" + data = mDBM.do_select(strsql,1) + if data[0] >= max_count: + reStatus = 0 + reMsg = f"已达到最多通道数量-{max_count}通道,不能再添加" + return jsonify({'status': reStatus, 'msg': reMsg}) strsql = (f"INSERT INTO channel (area_id,channel_name,ulr,'type',status) values " - f"({ret[0]},'{cName}','{Rtsp}',1,0);") + f"({area_id},'{cName}','{Rtsp}',1,0);") else: - strsql = (f"UPDATE channel SET area_id={ret[0]},channel_name='{cName}'" + strsql = (f"UPDATE channel SET area_id={area_id},channel_name='{cName}'" f",ulr='{Rtsp}' where ID={cid};") ret = mDBM.do_sql(strsql) if ret == True: @@ -68,18 +78,22 @@ async def channel_add(): #新增通道 -- 2024-8-1修改为与修改通道用一 if cid == -1: reMsg = '添加通道成功' # 对新增的视频通道进行视频采集和 - strsql = f"select ID from channel where area_id={ret[0]} and channel_name={cName};" + strsql = f"select ID from channel where area_id={area_id} and channel_name={cName};" data = mDBM.do_select(strsql, 1) if data: cid = data[0] mMM.start_work(cid) else: - print("这里不应该没有值!!!!") + print(f"这里不应该没有值!!!!area_id-{area_id},cName--{cName}") else: reMsg = '修改通道成功' #需要先停再启动---不区分有没有修改URL了,就当有修改使用 mMM.stop_work(cid) + start_time = time.time() mMM.start_work(cid) + end_time = time.time() + execution_time = end_time - start_time + print(f"开始一个通道线程,花费了: {execution_time} seconds") else: reStatus = 0 if cid == -1: @@ -93,12 +107,13 @@ async def channel_add(): #新增通道 -- 2024-8-1修改为与修改通道用一 @api.route('/channel/img',methods=['POST']) @login_required -async def channel_img(): +async def get_channel_img(): + '''获取一帧图片''' json_data = await request.get_json() cid = int(json_data.get('cid')) channel_data = mMM.verify_list.get_channel(cid) if channel_data: - # 执行视频传输 + # 读取一帧画面 ret,frame = channel_data.cap.read() if ret: # 将帧转换为JPEG格式 @@ -112,33 +127,6 @@ async def channel_img(): else: return jsonify({"error": "Channel not found"}), 500 -@api.route('/channel/change',methods=['POST']) -@login_required -async def channel_change(): #修改通道信息 -- 已弃用 - area_id = (await request.form)['area_id'] - channel_id = (await request.form)['channel_id'] - channel_name = (await request.form)['channel_name'] - url = (await request.form)['url'] - if mReM.is_valid_rtsp_url(url) is not True: - reStatus = 0 - reMsg = 'rtsp地址不合法' - return jsonify({'status': reStatus, 'msg': reMsg}) - strsql = f"select area_name from area where id = {area_id};" - ret = mDBM.do_select(strsql, 1) - if ret: - strsql = f"UPDATE channel SET area_id={area_id},channel_name='{channel_name}',ulr='{url}' where ID={channel_id};" - ret = mDBM.do_sql(strsql) - if ret == True: - reStatus = 1 - reMsg = '修改通道信息成' - else: - reStatus = 0 - reMsg = '修改通道信息失败,请联系技术支持!' - else: - reStatus = 0 - reMsg = '错误的通道ID,请修改' - return jsonify({'status': reStatus, 'msg': reMsg}) - @api.route('/channel/del',methods=['POST']) @login_required async def channel_del(): #删除通道 @@ -149,7 +137,7 @@ async def channel_del(): #删除通道 ret = mDBM.delchannel(cid) if ret == True: reStatus = 1 - reMsg = '删除通道信息成' + reMsg = '删除通道信息成功' else: reStatus = 0 reMsg = '删除通道信息失败,请联系技术支持!' @@ -180,7 +168,7 @@ async def channel_check(): #检查通道视频的在线情况--可以获取全 @api.route('/channel/C2M',methods=['POST']) @login_required -async def channel_to_model(): +async def get_ctm_data(): '''获取通道关联模型的相关数据''' json_data = await request.get_json() cid = int(json_data.get('cid')) @@ -212,9 +200,100 @@ async def channel_to_model(): redata = {"m_datas":m_datas,"c2m_data":c2m_data_json,"schedule":schedule} return jsonify(redata) +@api.route('/channel/chanegeC2M',methods=['POST']) +@login_required +async def change_c_t_m(): + ''' + 修改和新增与通道关联的算法模块 + :return: + ''' + json_data = await request.get_json() + model_name = json_data.get('model_name') + check_area = json_data.get('check_area') + polygon_str = json_data.get('polygon_str') + iou_thres = json_data.get('iou_thres') + conf_thres = json_data.get('conf_thres') + schedule = json_data.get('schedule') + cid = json_data.get('cid') + #返回数据 + reStatus = 0 + reMsg = "更新失败,请联系技术支持!" + + #开始更新--- 统一先停止原通道工作线程 + if model_name=="请选择": + strsql = f"select ID from channel2model where channel_id={cid};" + data = mDBM.do_select(strsql,1) + if data: + #需要删除数据 + ret = mDBM.delC2M(cid,1) #只是删除了数据库数据 + if ret: + #重启下通道的工作线程 + mMM.stop_work(cid) + mMM.start_work(cid) + reStatus = 1 + reMsg = "更新成功" + else: #原本就没数据 + reStatus = 1 + reMsg = "更新成功" + else: #新增关联或修改关联 + # 验证数据 + if conf_thres <= 0 or conf_thres >= 1 or iou_thres <= 0 or iou_thres >= 1: + reMsg = "阈值的有效范围是大于0,小于1;请输入正确的阈值" + return jsonify({'status': reStatus, 'msg': reMsg}) + c2m_id = updateModel(cid,model_name,check_area,polygon_str,conf_thres,iou_thres) #c2m表 + if c2m_id != 0: + ret = updataSchedule(c2m_id,schedule.replace("'", "\"")) #schedule表 + if ret: + # 重启下通道的工作线程 + mMM.stop_work(cid) + mMM.start_work(cid) + reStatus = 1 + reMsg = "更新成功" + return jsonify({'status': reStatus, 'msg': reMsg}) + + +def updataSchedule(c2m_id,schedule): + # schedule_data_str = ("{'6': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " + # "'0': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " + # "'1': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " + # "'2': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], " + # "'3': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]," + # "'4': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]," + # "'5': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}") + #先删 + strsql = f"delete from schedule where channel2model_id={c2m_id};" + mDBM.do_sql(strsql) + #再加 + json_object = json.loads(schedule) + for day, hours in json_object.items(): + for hour, status in enumerate(hours): + strsql = ( + f"insert into schedule (channel2model_id,day,hour,status) values ({c2m_id},'{day}',{hour},{status})" + f" on conflict(channel2model_id,day,hour) do update set status=excluded.status;") + ret = mDBM.do_sql(strsql) + if not ret: #插入失败后,需要删除所有数据 + strsql = f"delete from schedule where channel2model_id={c2m_id};" + mDBM.do_sql(strsql) + return ret + return 1 + +def updateModel(channel_id,model_name,check_area,polygon_str,conf_thres,iou_thres): + '''新增和修改通道关联的模型 ----约束:一个通道只能关联一个算法模型 + return 0 失败, 其他为c2m_id + ''' + reStatus = 0 + strsql = f"select ID from channel where ID={channel_id};" + if mDBM.do_select(strsql, 1): # 通道号在数据库中 + strsql = f"select ID from model where model_name = '{model_name}';" + data = mDBM.do_select(strsql, 1) + if data: #通道和模型都有对应数据 + reStatus = mDBM.updateC2M(channel_id, data[0],check_area,polygon_str,conf_thres,iou_thres) + return reStatus + @api.route('/channel/area/list',methods=['GET']) @login_required -async def channel_area_list(): #获取区域列表 +async def channel_area_list(): + '''获取所属区域list''' strsql = "select * from area;" datas = mDBM.do_select(strsql) reMsg = [{'id': data[0], 'area_name': data[1]} for data in datas] @@ -225,14 +304,20 @@ async def channel_area_list(): #获取区域列表 async def channel_area_change(): #修改区域名称 area_id = (await request.form)['id'] area_name = (await request.form)['name'] - strsql = f"update area set area_name='{area_name}' where id = {area_id};" - ret = mDBM.do_sql(strsql) - if ret == True: - reStatus = 1 - reMsg = '修改通道名称成功' - else: + strsql = f"select id from area where area_name='{area_name}';" + datas = mDBM.do_select(strsql) + if datas: reStatus = 0 - reMsg = '修改通道名称失败,请联系技术支持!' + reMsg = '区域名称重复,请修改!' + else: + strsql = f"update area set area_name='{area_name}' where id = {area_id};" + ret = mDBM.do_sql(strsql) + if ret == True: + reStatus = 1 + reMsg = '修改通道名称成功' + else: + reStatus = 0 + reMsg = '修改通道名称失败,请联系技术支持!' return jsonify({'status': reStatus, 'msg': reMsg}) @api.route('/channel/area/del',methods=['POST']) @@ -258,15 +343,22 @@ async def channel_area_del(): #删除区域 @api.route('/channel/area/add',methods=['POST']) @login_required async def channel_area_add(): #添加区域 - area_name = (await request.form)['name'] - strsql = f"insert into area (area_name) values ('{area_name}');" - ret = mDBM.do_sql(strsql) - if ret == True: - reStatus = 1 - reMsg = '新增区域成功' - else: + json_data = await request.get_json() + area_name = json_data.get('name') + strsql = f"select id from area where area_name='{area_name}';" + data = mDBM.do_select(strsql,1) + if data: reStatus = 0 - reMsg = '新增区域失败,请联系技术支持!' + reMsg = '区域名称重复,请修改!' + else: + strsql = f"insert into area (area_name) values ('{area_name}');" + ret = mDBM.do_sql(strsql) + if ret == True: + reStatus = 1 + reMsg = '新增区域成功' + else: + reStatus = 0 + reMsg = '新增区域失败,请联系技术支持!' return jsonify({'status': reStatus, 'msg': reMsg}) @api.route('/channel/model/list',methods=['GET']) @@ -279,17 +371,6 @@ async def channel_model_list(): #获取算法列表 reMsg = [{'ID': data[0], 'model_name': data[1],'version':data[2]} for data in datas] return jsonify(reMsg) -@api.route('/channel/model/linklist',methods=['GET']) -@login_required -async def channel_model_linklist(): #获取算法列表 --关联算法时展示 --没调用。。 - ID = request.args.get('ID') #通道ID - strsql = (f"select t1.ID,t2.model_name from channel2model t1 left join model t2 " - f"on t1.model_id=t2.ID where channel_id={ID};") - datas = mDBM.do_select(strsql) - reMsg = {} - if datas: - reMsg = [{'ID': data[0], 'model_name': data[1]} for data in datas] - return jsonify(reMsg) @api.route('/channel/model/linkmodel',methods=['POST']) #--没调用。。 @login_required diff --git a/web/API/model.py b/web/API/model.py index bc1c353..b03e1cf 100644 --- a/web/API/model.py +++ b/web/API/model.py @@ -1,9 +1,11 @@ import os +import shutil from quart import jsonify, request,session,flash,redirect from . import api from web.common.utils import login_required from core.DBManager import mDBM -from core.Upload_file import allowed_file,check_file,updata_model +from core.ModelManager import mMM +from core.Upload_file import allowed_file,check_file from myutils.ConfigManager import myCongif from werkzeug.utils import secure_filename @@ -16,99 +18,155 @@ async def model_list(): #获取算法列表 "proportion":data[4]} for data in datas] return jsonify(reMsg) -@api.route('/model/upload',methods=['POST']) +def restart_work(mid): + strsql = f"select channel_id from channel2model where model_id = {mid};" + datas = mDBM.do_select(strsql) + if datas: # 有关联 + print("有关联") + # 重启通道业务 + for data in datas: + mMM.restartC2M(data[0]) # 根该模型关联的所有通道都需要重启工作线程 + +@api.route('/model/add',methods=['POST']) @login_required -async def model_upload(): #上传算法文件--需要进行文件校验 +async def model_add(): #新增算法 + reStatus = 0 + reMsg = "有错误!" + form = await request.form + model_name = form['mName'] + files = await request.files + if 'file' not in files: + reMsg = '参数错误' + return jsonify({'status': reStatus, 'msg': reMsg}) + file = files['file'] + if file.filename == '': + reMsg = '没有选择文件' + return jsonify({'status': reStatus, 'msg': reMsg}) + #判断算法名称是否重复 + strsql = f"select ID from model where model_name='{model_name}';" + data = mDBM.do_select(strsql, 1) + if data: + reMsg = "算法名称重复,请修改!" + else: + if file and allowed_file(file.filename): + filename = secure_filename(file.filename) #安全过滤 + file_path = os.path.join(myCongif.get_data('UPLOAD_FOLDER'), filename) + await file.save(file_path) + #检查上传文件的合法性,若符合要求移动到正式路径 + filename_pre = filename.rsplit('.',1)[0] #除去到.zip + model_version, model_name_file, model_path = check_file(file_path,filename_pre,2) #itype--2 是算法模型升级 1-系统升级 + #删除压缩包 + os.remove(file_path) + if model_version and model_path: + #model表插入数据 + strsql = (f"insert into model (model_name,version,model_path) values " + f"('{model_name}','{model_version}','{model_path}');") + ret = mDBM.do_sql(strsql) + if ret: + reStatus = 1 + reMsg = '算法添加成功' + else: + reMsg = '插入数据库出错,请联系技术支持!!' + else: + reMsg = '升级包不合法,请重新上传!' + else: + reMsg = '只允许上传zip文件' + #新增算法,不需要处理通道关联的相关业务 + return jsonify({'status': reStatus, 'msg': reMsg}) + +@api.route('/model/upgrade',methods=['POST']) +@login_required +async def model_upgrade(): #升级算法,需要先上传算法文件 + reStatus = 0 + reMsg = "有错误!" form = await request.form - model_name = form['model_name'] + mid = form['mid'] files = await request.files if 'file' not in files: - flash('参数错误') - return redirect(request.url) + reMsg = '参数错误' + return jsonify({'status': reStatus, 'msg': reMsg}) file = files['file'] if file.filename == '': - flash('没有选择文件') - return redirect(request.url) + reMsg = '没有选择文件' + return jsonify({'status': reStatus, 'msg': reMsg}) if file and allowed_file(file.filename): - filename = secure_filename(file.filename) + filename = secure_filename(file.filename) # 安全过滤 file_path = os.path.join(myCongif.get_data('UPLOAD_FOLDER'), filename) await file.save(file_path) - if check_file(file_path,2): #itype--2 是算法模型升级 - strsql = (f"insert into upgrade (itype,filepath,model_name) values (2,'{file_path}','{model_name}')" - f" on conflict(itype,model_name) do update set filepath=excluded.filepath;") + # 检查上传文件的合法性,若符合要求移动到正式路径 + filename_pre = filename.rsplit('.', 1)[0] # 除去到.zip + model_version, model_name_file, model_path = check_file(file_path, filename_pre, 2) # itype--2 是算法模型升级 1-系统升级 + # 删除压缩包 + os.remove(file_path) + if model_version and model_path: + strsql = (f"update model set version='{model_version}',model_path='{model_path}' " + f"where ID={mid};") ret = mDBM.do_sql(strsql) - # session['model'] = file_path if ret: - strsql = f"select id from upgrade where itype=2 and model_name='{model_name}';" - data=mDBM.do_select(strsql,1) - reStatus = data[0] - reMsg = "升级包上传成功" + reStatus = 1 + reMsg = '升級算法成功' + #重启业务数据 + restart_work(mid) else: - reStatus = 0 - reMsg = "升级包上传失败" - return jsonify({'status': reStatus, 'msg': reMsg}) + reMsg = '修改数据库出错,请联系技术支持!!' else: - flash('升级包不合法,请重新上传') - # return redirect(url_for('main.get_html', html='系统管理.html')) - return redirect(request.url) + reMsg = '升级包不合法,请重新上传!' else: - flash('只允许上传zip文件') - return redirect(request.url) + reMsg = '只允许上传zip文件' -@api.route('/model/add',methods=['POST']) -@login_required -async def model_add(): #新增算法,需要先上传算法文件 - model_name = (await request.form)['model_name'] - upgrade_id = (await request.form)['upgrade_id'] #升级文件ID - ###---需要根据升级包获取模型文件路径,算法版本号等信息,若根据upgrade_id获取不了对应的信息,则返回报错 - ### - strsql = f"select ID from model where model_name='{model_name}';" - data = mDBM.do_select(strsql,1) - if data: - reStatus = 0 - reMsg = "算法名称重复,请修改!" - else: - strsql = f"insert into model (model_name) values ('{model_name}');" #还有参数未写全 - ret = mDBM.do_sql(strsql) - if ret: - reStatus = 1 - reMsg = "新增算法成功!" - else: - reStatus = 0 - reMsg = "新增算法失败,请联系技术支持!" return jsonify({'status': reStatus, 'msg': reMsg}) -@api.route('/model/upgrade',methods=['POST']) +@api.route('/model/del',methods=['POST']) @login_required -async def model_upgrade(): #升级算法,需要先上传算法文件 - return jsonify(1) +async def model_del(): + json_data = await request.get_json() + mid = json_data.get('mid') + #删除与该算法关联的通道相关数据 + strsql = f"select channel_id from channel2model where model_id = {mid};" + datas = mDBM.do_select(strsql) + if datas: #有关联 + #删与通道的关联信息 --c2m,schedule + mDBM.delC2M(mid,2) + #重启通道业务 + for data in datas: + mMM.restartC2M(data[0]) #根该模型关联的所有通道都需要重启工作线程 -@api.route('/model/config',methods=['GET']) -@login_required -async def model_config(): #获取算法的配置信息 --- list已经获取 - ID = request.args.get('ID') - strsql = f"select model_name,version,duration_time,proportion from model where ID={ID};" + #删除算法文件 + strsql = f"select model_path from model where ID = {mid};" data = mDBM.do_select(strsql,1) - reMsg = {"model_name":data[0],"version":data[1],"duration_time":data[2],"proportion":data[3]} - return jsonify(reMsg) + if data: + py_path = data[0] + dir_path = py_path.rsplit('/',1)[0] #正常最后一层应该都是/--手动加的 + print(dir_path) + shutil.rmtree(dir_path) + # 删该算法记录 + strsql = f"delete from model where ID = {mid};" + mDBM.do_sql(strsql) + #正常来说删除一般不会失败 + return jsonify({'status': 1, 'msg': "删除成功"}) @api.route('/model/changecnf',methods=['POST']) @login_required async def model_config_change(): #修改算法的配置信息 - ID = (await request.form)['ID'] - duration_time = (await request.form)['duration_time'] - proportion = float((await request.form)['proportion']) - if proportion>0 and proportion < 1: - strsql = f"update model set duration_time='{duration_time}',proportion='{proportion}' where ID={ID};" - ret = mDBM.do_sql(strsql) - if ret: - reStatus = 1 - reMsg = "修复算法配置成功" + json_data = await request.get_json() + mid = json_data.get('mid') + reStatus = 0 + try: + duration_time = int(json_data.get('duration_time')) + proportion = float(json_data.get('proportion')) + if proportion > 0 and proportion < 1: + strsql = f"update model set duration_time='{duration_time}',proportion='{proportion}' where ID={mid};" + ret = mDBM.do_sql(strsql) + if ret: + reStatus = 1 + reMsg = "修改算法配置成功" + #重启-工作线程 + restart_work(mid) + else: + reMsg = "修改算法配置失败" else: - reStatus = 0 - reMsg = "修复算法配置失败" - else: - reStatus = 0 - reMsg = "占比需要为大于0,小于1的值" + reMsg = "占比阈值需要为大于0,小于1的值" + except ValueError: + reMsg = "数据类型不对!" return jsonify({'status': reStatus, 'msg': reMsg}) diff --git a/web/API/system.py b/web/API/system.py index 05cae78..573902d 100644 --- a/web/API/system.py +++ b/web/API/system.py @@ -6,6 +6,7 @@ from core.DBManager import mDBM from core.Upload_file import allowed_file,check_file,update_system from myutils.ConfigManager import myCongif from myutils.ReManager import mReM +from myutils.IPManager import IPM from werkzeug.utils import secure_filename @api.route('/system/info',methods=['GET']) @@ -15,11 +16,28 @@ async def system_info(): #获取系统信息 data = mDBM.do_select(strsql,1) strRet = "" if data: - strRet = {"ID":data[0],"version":data[1],"dev_ip":data[2],"dev_mask":data[3],"dev_gateway":data[4], - "server_ip":data[5],"server_port":data[6]} + #获取wifilist + wifilist = IPM.get_wifi_list() + connected_wifi = IPM.get_connected_wifi() + print(connected_wifi) + + strRet = {"ID":data[0],"version":data[1],"wired_type":data[2],"wired_ip":data[3],"wired_mask":data[4], + "wired_gateway":data[5],"wired_dns":data[6],"wireless_type":data[7],"wireless_ip":data[8],"wireless_mask":data[9], + "wireless_gateway":data[10],"wireless_dns":data[11],"service_ip":data[12],"service_port":data[13], + "ssid":connected_wifi,"wifi_passwd":data[15],"wifi_list":wifilist} return jsonify(strRet) #它将Python对象转换为JSON格式的字符串,并将其作为HTTP响应的主体返回给客户端, # 同时设置正确的Content-Type响应头,表明响应主体是JSON格式的数据。 +@api.route('/system/area',methods=['GET']) +@login_required +async def area_info(): #获取系统信息 + strsql = "select * from area;" + datas = mDBM.do_select(strsql) + strRet = "" + if datas: + strRet = [{'ID':data[0],'area_name':data[1]} for data in datas] + return jsonify(strRet) + @api.route('/system/upload',methods=['POST']) @login_required async def system_upload(): #上传系统升级文件 diff --git a/web/API/user.py b/web/API/user.py index 0d53778..77dc6ea 100644 --- a/web/API/user.py +++ b/web/API/user.py @@ -1,4 +1,5 @@ import os +import hashlib from quart import Quart, render_template, request, session, redirect, url_for,jsonify,send_file,flash from quart_sqlalchemy import SQLAlchemy from quart_session import Session @@ -39,8 +40,9 @@ async def user_login(): #用户登录 #比对用户名和密码 strsql = f"select password from user where username = '{username}'" db_password = mDBM.do_select(strsql,1) + passwd_md5 = get_md5(password) if db_password: - if db_password[0] == password: #后续需要对密码进行MD5加默 + if db_password[0] == passwd_md5: #后续需要对密码进行MD5加默 print("登录成功") session['user'] = username return redirect(url_for('main.get_html', html='view_main.html')) @@ -86,19 +88,29 @@ async def user_adduser(): #新增用户 @api.route('/user/passwd',methods=['POST']) @login_required -async def user_change_passwd(): #重置密码 - username = (await request.form)['username'] - password = myCongif.get_data('pw') - strsql = f"update user set password='{password}' where username='{username}';" - ret = mDBM.do_sql(strsql) - if ret == True: - reStatus = 1 - reMsg = '重置密码成功' +async def user_change_passwd(): #修改密码 + json_data = await request.get_json() + oldpasswd = json_data.get('oldpasswd') + newpasswd = json_data.get('newpasswd') + old_md5= get_md5(oldpasswd) + print(old_md5) + strsql = f"select id from user where password='{old_md5}';" + data = mDBM.do_select(strsql,1) + reStatus = 0 + if data: + new_md5 = get_md5(newpasswd) + strsql = f"update user set password = '{new_md5}' where password = '{old_md5}';" + ret = mDBM.do_sql(strsql) + if ret: + reStatus = 1 + reMsg = '修改密码成功' + else: + reMsg = '修改密码失败,请联系技术支持!' else: - reStatus = 0 - reMsg = '重置密码失败,请联系管理员处理!' + reMsg = '原密码错误,请确认!' return jsonify({'status':reStatus,'msg':reMsg}) + @api.route('/user/changeuser',methods=['POST']) @login_required async def user_change_user_info(): #修改用户信息 @@ -124,4 +136,9 @@ async def get_user(user_id): else: return jsonify({'error': 'User not found'}), 404 except Exception as e: - return handle_error(e) \ No newline at end of file + return handle_error(e) + +def get_md5(value): + md5 = hashlib.md5() # 创建一个md5对象 + md5.update(value.encode('utf-8')) # 使用utf-8编码更新待计算的字符串 + return md5.hexdigest() # 返回十六进制的MD5值 \ No newline at end of file diff --git a/web/API/viedo.py b/web/API/viedo.py index 821da64..565ad76 100644 --- a/web/API/viedo.py +++ b/web/API/viedo.py @@ -14,38 +14,6 @@ logger = logging.getLogger(__name__) #pcs = set() #创建一个空的集合,去重复且无序 pcs = {} -''' ---------------基础信息--后续封装在函数里--------------- -''' -# 打开摄像头 -# def get_camera(): -# cap = cv2.VideoCapture(0) -# if not cap.isOpened(): -# raise IOError("Cannot open webcam") -# return cap -# -# cap = get_camera() -# last_image = None -# read_lock = threading.Lock() -# def camera_thread(): -# global cap, last_image -# while True: -# try: -# ret, frame = cap.read() -# if not ret: -# logger.warning("Camera disconnected. Reconnecting...") -# cap.release() -# cap = get_camera() -# continue -# frame = cv2.resize(frame, (640, 480)) # 降低视频分辨率 -# with read_lock: -# last_image = frame -# time.sleep(1.0/20) -# except Exception as e: -# logger.error(f"Error in camera thread: {e}") -# continue - -#threading.Thread(target=camera_thread, daemon=True).start() ''' ---------------------传输-------------------------- ''' @@ -146,42 +114,50 @@ async def get_stats(peer_connection): async def ws_video_feed(channel_id): print(f"New connection for channel: {channel_id}") channel_data = mMM.verify_list.get_channel(channel_id) - if channel_data: - verify_rate = int(myCongif.get_data("verify_rate")) - frame_interval = 1.0 / verify_rate #用于帧率控制 - error_max_count = verify_rate * int(myCongif.get_data("video_error_count")) #视频帧捕获失败触发提示的上限 - sleep_time = int(myCongif.get_data("cap_sleep_time")) - last_frame_time = time.time() # 初始化个读帧时间 - icount = 0 - while channel_data.bool_run: #这里的多线程并发,还需要验证检查 - # 帧率控制帧率 - current_time = time.time() - elapsed_time = current_time - last_frame_time - if elapsed_time < frame_interval: - await asyncio.sleep(frame_interval - elapsed_time) # 若小于间隔时间则休眠 - last_frame_time = time.time() - #执行视频传输 - frame = channel_data.get_last_frame() - if frame is not None: - #img = frame.to_ndarray(format="bgr24") - # ret, buffer = cv2.imencode('.jpg', frame) - # if not ret: - # continue - # frame = buffer.tobytes() - icount = 0 - await websocket.send(frame) - else: - icount += 1 - if icount > error_max_count: + try: + if channel_data: + verify_rate = int(myCongif.get_data("verify_rate")) + error_max_count = verify_rate * int(myCongif.get_data("video_error_count")) #视频帧捕获失败触发提示的上限 + sleep_time = int(myCongif.get_data("cap_sleep_time")) + frame_interval = 1.0 / verify_rate #用于帧率控制 + last_frame_time = time.time() # 初始化个读帧时间 + icount = 0 + while True: #这里的多线程并发,还需要验证检查 + # 帧率控制帧率 ---输出暂时不控制帧率,有就传输 + current_time = time.time() + elapsed_time = current_time - last_frame_time + if elapsed_time < frame_interval: + await asyncio.sleep(frame_interval - elapsed_time) # 若小于间隔时间则休眠 + last_frame_time = time.time() + #执行视频传输 + frame = channel_data.get_last_frame() + if frame is not None: + #img = frame.to_ndarray(format="bgr24") + # ret, buffer = cv2.imencode('.jpg', frame) + # if not ret: + # continue + # frame = buffer.tobytes() icount = 0 - error_message = b"video_error" - await websocket.send(error_message) - await asyncio.sleep(sleep_time*1000) #等待视频重连时间 - else: - print("没有通道数据!") - error_message = b"client_error" - await websocket.send(error_message) - await asyncio.sleep(0.1) #等0.1秒前端处理时间 + await websocket.send(frame) + else: + #print("frame is None") + icount += 1 + if icount > error_max_count: + print("视频源无图像") + icount = 0 + error_message = b"video_error" + await websocket.send(error_message) + await asyncio.sleep(sleep_time) #等待视频重连时间 + #await asyncio.sleep(0.02) + else: + print("没有通道数据!") + error_message = b"client_error" + await websocket.send(error_message) + await asyncio.sleep(0.1) #等0.1秒前端处理时间 + except Exception as e: + print(f"WebSocket connection for channel {channel_id} closed: {e}") + finally: + print(f"Cleaning up resources for channel {channel_id}") @api.route('/shutdown', methods=['POST']) async def shutdown():#这是全关 --需要修改 @@ -216,7 +192,7 @@ async def start_stream(): #开启视频通道,把视频通道编号和元素 strsql = f"select element_id from channel where ID = {channel_id};" data = mDBM.do_select(strsql,1) if data: - if data[0] == '': + if not data[0] or data[0] == '': strsql = f"update channel set element_id = '{element_id}' where ID={channel_id};" ret = mDBM.do_sql(strsql) if ret == True: @@ -236,7 +212,6 @@ async def close_stream(): #关闭视频通道 element_id = json_data.get('element_id') reStatus = 0 reMsg ="" - #?关闭视频播放--业务逻辑-待确认后端是否需要执行 #数据库中该通道的关联关系要清除 strsql = f"update channel set element_id = '' where element_id={element_id};" ret = mDBM.do_sql(strsql) @@ -245,4 +220,6 @@ async def close_stream(): #关闭视频通道 reMsg = '关闭画面成功!' else: reMsg = '删除通道与组件关联关系失败,请联系技术支持!' + # ?关闭视频播放--业务逻辑-待确认后端是否需要执行 + return jsonify({'status': reStatus, 'msg': reMsg}) diff --git a/web/main/static/resources/chrome/allow-access.png b/web/main/static/resources/chrome/allow-access.png deleted file mode 100644 index eaa707f..0000000 Binary files a/web/main/static/resources/chrome/allow-access.png and /dev/null differ diff --git a/web/main/static/resources/chrome/axure-chrome-extension.crx b/web/main/static/resources/chrome/axure-chrome-extension.crx deleted file mode 100644 index fde7743..0000000 Binary files a/web/main/static/resources/chrome/axure-chrome-extension.crx and /dev/null differ diff --git a/web/main/static/resources/chrome/axure_logo.png b/web/main/static/resources/chrome/axure_logo.png deleted file mode 100644 index 0882a16..0000000 Binary files a/web/main/static/resources/chrome/axure_logo.png and /dev/null differ diff --git a/web/main/static/resources/chrome/chrome.html b/web/main/static/resources/chrome/chrome.html deleted file mode 100644 index e9a3ede..0000000 --- a/web/main/static/resources/chrome/chrome.html +++ /dev/null @@ -1,187 +0,0 @@ -<html> -<head> - <title>Install the Axure RP Chrome Extension</title> - <style type="text/css"> - * - { - font-family: NunitoSans, Helvetica, Arial, sans-serif; - } - body - { - text-align: center; - background-color: #fafafa; - } - p - { - font-size: 14px; - line-height: 18px; - color: #333333; - } - div.container - { - width: 980px; - margin-left: auto; - margin-right: auto; - text-align: left; - } - a - { - text-decoration: none; - color: #009dda; - } - .button - { - background: #A502B3; - font: normal 16px Arial, sans-serif; - color: #FFFFFF; - padding: 10px 30px 10px 30px; - border: 2px solid #A502B3; - display: inline-block; - margin-top: 10px; - text-transform: uppercase; - font-size: 14px; - border-radius: 4px; - } - a:hover.button - { - border: 2px solid #A502B3; - color: #A502B3; - background-color: #FFFFFF; - } - div.left - { - width: 400px; - float: left; - margin-right: 80px; - } - div.right - { - width: 400px; - float: left; - } - div.buttonContainer - { - text-align: center; - } - h1 - { - font-size: 36px; - color: #333333; - line-height: 50px; - margin-bottom: 20px; - font-weight: normal; - } - h2 - { - font-size: 24px; - font-weight: normal; - color: #08639C; - text-align: center; - } - h3 - { - font-size: 16px; - color: #333333; - font-weight: normal; - text-transform: uppercase; - } - .heading - { - border-bottom: 1px solid black; - height: 36px; - line-height: 36px; - font-size: 22px; - color: #000000; - - } - span.faq - { - font-size: 16px; - line-height: 24px; - font-weight: normal; - text-transform: uppercase; - color: #333333; - display: block; - } - </style> -</head> -<body> - <div class="container"> - <br /> - <br /> - <img src="axure_logo.png" alt="axure" /> - <br /> - <br /> - <h1> - AXURE RP EXTENSION FOR CHROME</h1> - <p style="font-size: 14px; color: #666666; margin-top: 10px;"> - Google Chrome requires an extension to view locally stored projects. Alternatively, - upload your RP file to <a href="https://www.axure.cloud">Axure Cloud</a> or use a different - browser. You can also Preview from Axure RP.</p> - <img src="preview-rp.png" alt="preview"/> - <h3 class="heading"> - VIEW LOCAL PROJECTS IN CHROME</h3> - <div class="left"> - <h3> - 1. Install Extension from Chrome Store</h3> - <div class="buttonContainer"> - <a class="button" href="https://chrome.google.com/webstore/detail/dogkpdfcklifaemcdfbildhcofnopogp" - target="_blank">Install Extension</a> - </div> - </div> - <div class="right"> - <h3> - 2. Open "More Tools > Extensions"</h3> - <img src="extensions.png" alt="extensions"/> - </div> - <div style="clear: both; height: 20px;"> - </div> - <div class="left"> - <h3> - 3. View Axure RP Extension Details</h3> - <img src="details.png" alt="extension details"/> - </div> - <div class="right"> - <h3> - 4. Check "Allow access to file URLs"</h3> - <img src="allow-access.png" alt="allow access"/> - </div> - <div style="clear: both; height: 20px;"> - </div> - <div class="left"> - <h3> - 5. Click the button below</h3> - <div class="buttonContainer"> - <a class="button" href="../../start.html">View in Chrome</a> - </div> - </div> - <div style="clear: both; height: 20px;"> - </div> - <h3 class="heading"> - EXTENSION FAQ</h3> - <p> - <span class="faq">What is a Chrome Extension?</span> Extensions are downloadable - plug-ins for Google Chrome that modify the browser - and allow you additional capabilities. - </p> - <p style="margin-top: 25px;"> - <span class="faq">Why do I need to install the extension?</span> Google requires - this extension to be installed to allow the viewing of local files in - Chrome - </p> - <p style="margin-top: 25px; margin-bottom: 25px;"> - <span class="faq">Why does this extension require a high access level?</span> This - extension requires a high access level to allow the viewing of the file:// - protocol. Axure does not track or access any of your information. - </p> - <h3 class="heading"> - WE'RE HERE TO HELP</h3> - <p> - Need help or have any questions? Contact our support team at <a href="mailto:support@axure.com"> - support@axure.com</a>. - </p> - <div style="clear: both; height: 20px;"> - </div> - </div> -</body> -</html> diff --git a/web/main/static/resources/chrome/details.png b/web/main/static/resources/chrome/details.png deleted file mode 100644 index 260397f..0000000 Binary files a/web/main/static/resources/chrome/details.png and /dev/null differ diff --git a/web/main/static/resources/chrome/extensions.png b/web/main/static/resources/chrome/extensions.png deleted file mode 100644 index 4b011c9..0000000 Binary files a/web/main/static/resources/chrome/extensions.png and /dev/null differ diff --git a/web/main/static/resources/chrome/firefox.html b/web/main/static/resources/chrome/firefox.html deleted file mode 100644 index cbf33b5..0000000 --- a/web/main/static/resources/chrome/firefox.html +++ /dev/null @@ -1,130 +0,0 @@ -<html> -<head> - <title>Axure RP - Firefox Local File Restrictions</title> - <style type="text/css"> - * - { - font-family: Helvetica, Arial, sans-serif; - } - body - { - text-align: center; - background-color: #fafafa; - } - p - { - font-size: 14px; - line-height: 18px; - color: #333333; - } - div.container - { - width: 980px; - margin-left: auto; - margin-right: auto; - text-align: left; - } - a - { - text-decoration: none; - color: #009dda; - } - .button - { - background: #A502B3; - font: normal 16px Arial, sans-serif; - color: #FFFFFF; - padding: 10px 30px 10px 30px; - border: 2px solid #A502B3; - display: inline-block; - margin-top: 10px; - text-transform: uppercase; - font-size: 14px; - border-radius: 4px; - } - a:hover.button - { - border: 2px solid #A502B3; - color: #A502B3; - background-color: #FFFFFF; - } - div.left - { - width: 400px; - float: left; - margin-right: 80px; - } - div.right - { - width: 400px; - float: left; - } - div.buttonContainer - { - text-align: center; - } - h1 - { - font-size: 36px; - color: #333333; - line-height: 50px; - margin-bottom: 20px; - font-weight: normal; - } - h2 - { - font-size: 24px; - font-weight: normal; - color: #08639C; - text-align: center; - } - h3 - { - font-size: 16px; - line-height: 24px; - color: #333333; - font-weight: normal; - } - .heading - { - border-bottom: 1px solid black; - height: 36px; - line-height: 36px; - font-size: 22px; - color: #000000; - } - span.faq - { - font-size: 16px; - font-weight: normal; - text-transform: uppercase; - color: #333333; - display: block; - } - </style> -</head> -<body> - <div class="container"> - <br /> - <br /> - <img src="axure_logo.png" alt="axure" /> - <br /> - <h1> - FIREFOX LOCAL FILE RESTRICTIONS</h1> - <p style="font-size: 16px; line-height: 24px; color: #666666; margin-top: 10px;"> - Firefox does not permit locally stored files to be viewed. Use Preview to view your projects in progress. -<img src="preview-rp.png" alt="preview"/> - </p> - <p style="font-size: 16px; line-height: 24px; color: #666666; margin-top: 10px;"> - Alternatively, you can choose a different web browser, upload your RP file to <a href="https://app.axure.cloud">Axure Cloud</a> or publish the local files to a web server.</p> - <h3 class="heading"> - We're Here to Help</h3> - <p> - Need help or have any questions? Drop us a line at <a href="mailto:support@axure.com"> - support@axure.com</a>. - </p> - <div style="clear: both; height: 20px;"> - </div> - </div> -</body> -</html> diff --git a/web/main/static/resources/chrome/preview-rp.png b/web/main/static/resources/chrome/preview-rp.png deleted file mode 100644 index 78f3704..0000000 Binary files a/web/main/static/resources/chrome/preview-rp.png and /dev/null differ diff --git a/web/main/static/resources/chrome/safari.html b/web/main/static/resources/chrome/safari.html deleted file mode 100644 index b828eeb..0000000 --- a/web/main/static/resources/chrome/safari.html +++ /dev/null @@ -1,155 +0,0 @@ -<html> -<head> - <title>Axure RP - Safari Local File Restrictions</title> - <style type="text/css"> - * - { - font-family: Helvetica, Arial, sans-serif; - } - body - { - text-align: center; - background-color: #fafafa; - } - p - { - font-size: 14px; - line-height: 18px; - color: #333333; - } - div.container - { - width: 980px; - margin-left: auto; - margin-right: auto; - text-align: left; - } - a - { - text-decoration: none; - color: #009dda; - } - .button - { - background: #A502B3; - font: normal 16px Arial, sans-serif; - color: #FFFFFF; - padding: 10px 30px 10px 30px; - border: 2px solid #A502B3; - display: inline-block; - margin-top: 10px; - text-transform: uppercase; - font-size: 14px; - border-radius: 4px; - } - a:hover.button - { - border: 2px solid #A502B3; - color: #A502B3; - background-color: #FFFFFF; - } - div.left - { - width: 400px; - float: left; - margin-right: 80px; - } - div.right - { - width: 400px; - float: left; - } - div.buttonContainer - { - text-align: center; - } - h1 - { - font-size: 36px; - color: #333333; - line-height: 50px; - margin-bottom: 20px; - font-weight: normal; - } - h2 - { - font-size: 24px; - font-weight: normal; - color: #08639C; - text-align: center; - } - h3 - { - font-size: 16px; - line-height: 24px; - color: #333333; - font-weight: normal; - } - .heading - { - border-bottom: 1px solid black; - height: 36px; - line-height: 36px; - font-size: 22px; - color: #000000; - } - span.faq - { - font-size: 16px; - font-weight: normal; - text-transform: uppercase; - color: #333333; - display: block; - } - </style> -</head> -<body> - <div class="container"> - <br /> - <br /> - <img src="axure_logo.png" alt="axure" /> - <br /> - <h1> - SAFARI LOCAL FILE RESTRICTIONS</h1> - <p style="font-size: 16px; line-height: 24px; color: #666666; margin-top: 10px;"> - To view locally stored projects in Safari, you will need to "disable local file restrictions". Alternatively, - you can upload your RP file to <a href="https://www.axure.cloud">Axure Cloud</a> or publish the local files to a web server. You can also Preview from Axure RP.</p> - <img src="preview-rp.png" alt="preview"/> - <h3 class="heading"> - VIEW LOCAL PROJECTS IN SAFARI</h3> - <div class=""> - <h3> - 1. Open "Safari > Preferences > Advanced" from the top menu, and check the option to "Show Develop menu in menu bar"</h3> - <img src="safari_advanced.png" alt="advanced" /> - </div> - <div style="clear: both; height: 20px;"> - - </div> - <div class=""> - <h3> - 2. In the Develop menu that appears in the menu bar, click "Develop > Disable Local File Restrictions" to un-select the menu option</h3> - <img src="safari_restrictions.png" alt="extensions" /> - </div> - <div style="clear: both; height: 20px;"> - </div> - <div class="left"> - <h3> - 3. Click the button below - </h3> - <div class="buttonContainer"> - <a class="button" href="../../start.html">View in Safari</a> - </div> - </div> - <div style="clear: both; height: 20px;"> - </div> - <h3 class="heading"> - We're Here to Help</h3> - <p> - Need help or have any questions? Drop us a line at <a href="mailto:support@axure.com"> - support@axure.com</a>. - </p> - <div style="clear: both; height: 20px;"> - </div> - </div> -</body> -</html> diff --git a/web/main/static/resources/chrome/safari_advanced.png b/web/main/static/resources/chrome/safari_advanced.png deleted file mode 100644 index 9f81b2a..0000000 Binary files a/web/main/static/resources/chrome/safari_advanced.png and /dev/null differ diff --git a/web/main/static/resources/chrome/safari_restrictions.png b/web/main/static/resources/chrome/safari_restrictions.png deleted file mode 100644 index 26ddf3f..0000000 Binary files a/web/main/static/resources/chrome/safari_restrictions.png and /dev/null differ diff --git a/web/main/static/resources/chrome/splitter.gif b/web/main/static/resources/chrome/splitter.gif deleted file mode 100644 index 3f8bca9..0000000 Binary files a/web/main/static/resources/chrome/splitter.gif and /dev/null differ diff --git a/web/main/static/resources/chrome/splitter.png b/web/main/static/resources/chrome/splitter.png deleted file mode 100644 index 8e354e7..0000000 Binary files a/web/main/static/resources/chrome/splitter.png and /dev/null differ diff --git a/web/main/static/resources/scripts/aiortc-client-new.js b/web/main/static/resources/scripts/aiortc-client-new.js index 720c566..55cf4cc 100644 --- a/web/main/static/resources/scripts/aiortc-client-new.js +++ b/web/main/static/resources/scripts/aiortc-client-new.js @@ -4,6 +4,17 @@ var channel_list = null; const fourViewButton = document.getElementById('fourView'); const nineViewButton = document.getElementById('nineView'); +//页面即将卸载时执行 +window.addEventListener('beforeunload', function (event) { + // 关闭所有 WebSocket 连接或执行其他清理操作 + for(let key in video_list){ + delete run_list[key]; + video_list[key].close(); + delete video_list[key]; + } +}); + +//页面加载时执行 document.addEventListener('DOMContentLoaded', async function() { console.log('DOM fully loaded and parsed'); // 发送请求获取额外数据 --- 这个接口功能有点大了---暂时只是更新通道树2024-7-29 @@ -53,6 +64,8 @@ document.addEventListener('DOMContentLoaded', async function() { } }); + + //视频窗口 document.getElementById('fourView').addEventListener('click', function() { if (fourViewButton.classList.contains('btn-primary')) { @@ -255,39 +268,51 @@ function connectToStream(element_id,channel_id,channel_name) { const socket = new WebSocket(streamUrl); video_list[element_id] = socket; run_list[element_id] = true; + imgElement.style.display = 'block'; + berror_state = false; // 处理连接打开事件 socket.onopen = () => { console.log('WebSocket connection established'); }; socket.onmessage = function(event) { - // 释放旧的对象URL---需要吗? -// if (imgElement.src) { -// URL.revokeObjectURL(imgElement.src); -// } const reader = new FileReader(); + reader.readAsArrayBuffer(event.data); + reader.onload = () => { const arrayBuffer = reader.result; const decoder = new TextDecoder("utf-8"); const decodedData = decoder.decode(arrayBuffer); if (decodedData === "video_error") { //video_error - displayErrorMessage(imgElement, "该视频源未获取到画面,请检查,默认5分钟后重新链接视频源。"); + displayErrorMessage(imgElement, "该视频源未获取到画面,请检查,默认每隔2分钟将重新链接视频源。"); + berror_state = true; } else if(decodedData === "client_error"){ //client_error run_list[element_id] = false; displayErrorMessage(imgElement, "该通道节点数据存在问题,请重启或联系技术支持!"); socket.close(); // 停止连接 + berror_state = true; } else { - const blob = new Blob([arrayBuffer], { type: 'image/jpeg' }); - const imageUrl = URL.createObjectURL(blob); - imgElement.src = imageUrl; - imgElement.style.display = 'block'; -// imgElement.src = URL.createObjectURL(result); -// imgElement.style.display = 'block'; + if(berror_state){ + removeErrorMessage(imgElement); + berror_state = false; + } + // 释放旧的对象URL + if (imgElement.src) { + URL.revokeObjectURL(imgElement.src); + } + //blob = new Blob([arrayBuffer], { type: 'image/jpeg' }); + imgElement.src = URL.createObjectURL(event.data); } }; - reader.readAsArrayBuffer(event.data); + + //图片显示方案二 +// if (imgElement.src) { +// URL.revokeObjectURL(imgElement.src); +// } +// imgElement.src = URL.createObjectURL(event.data); + }; socket.onclose = function() { diff --git a/web/main/static/resources/scripts/axure/action.js b/web/main/static/resources/scripts/axure/action.js deleted file mode 100644 index 14b3264..0000000 --- a/web/main/static/resources/scripts/axure/action.js +++ /dev/null @@ -1,2115 +0,0 @@ -$axure.internal(function($ax) { - var _actionHandlers = {}; - var _action = $ax.action = {}; - - var queueTypes = _action.queueTypes = { - none: 0, - move: 1, - setState: 2, - fade: 3, - resize: 4, - rotate: 5 - }; - - var animationQueue = {}; - - // using array as the key doesn't play nice - var nextAnimationId = 1; - var animationsToCount = {}; - var actionToActionGroups = {}; - var getAnimation = function(id, type) { - return animationQueue[id] && animationQueue[id][type] && animationQueue[id][type][0]; - }; - - var _addAnimation = _action.addAnimation = function (id, type, func, suppressFire) { - - var wasEmpty = !getAnimation(id, type); - // Add the func to the queue. Create the queue if necessary. - var idQueue = animationQueue[id]; - if(!idQueue) animationQueue[id] = idQueue = {}; - - var queue = idQueue[type]; - if(!queue) idQueue[type] = queue = []; - - queue[queue.length] = func; - // If it was empty, there isn't a callback waiting to be called on this. You have to fire it manually. - // If this is waiting on something, suppress it, and it will fire when it's ready - if(wasEmpty && !suppressFire) func(); - }; - - var _addAnimations = function (animations) { - if(animations.length == 1) { - _addAnimation(animations[0].id, animations[0].type, animations[0].func); - return; - } - var allReady = true; - var readyCount = 0; - for(var i = 0; i < animations.length; i++) { - var animation = animations[i]; - var thisReady = !getAnimation(animation.id, animation.type); - allReady = allReady && thisReady; - if (thisReady) readyCount++; - else { - var typeToGroups = actionToActionGroups[animation.id]; - if (!typeToGroups) actionToActionGroups[animation.id] = typeToGroups = {}; - - var groups = typeToGroups[animation.type]; - if (!groups) typeToGroups[animation.type] = groups = []; - - groups[groups.length] = animations; - } - } - - for(i = 0; i < animations.length; i++) { - animation = animations[i]; - _addAnimation(animation.id, animation.type, animation.func, true); - } - - if (allReady) { - for (i = 0; i < animations.length; i++) animations[i].func(); - } else { - animations.id = nextAnimationId++; - animationsToCount[animations.id] = readyCount; - } - } - - var _fireAnimationFromQueue = _action.fireAnimationFromQueue = function (id, type) { - // Remove the function that was just fired - if (animationQueue[id] && animationQueue[id][type]) $ax.splice(animationQueue[id][type], 0, 1); - - // Fire the next func if there is one - var func = getAnimation(id, type); - if(func && !_checkFireActionGroup(id, type, func)) func(); - }; - - var _checkFireActionGroup = function(id, type, func) { - var group = actionToActionGroups[id]; - group = group && group[type]; - if (!group || group.length == 0) return false; - - var animations = group[0]; - var found = false; - for (var i = 0; i < animations.length; i++) { - var animation = animations[i]; - if (animation.id == id && animation.type == type) { - found = func == animation.func; - break; - } - } - - // if found then update this action group, otherwise, keep waiting for right action to fire - if(!found) return false; - $ax.splice(group, 0, 1); - var count = animationsToCount[animations.id] + 1; - if(count != animations.length) { - animationsToCount[animations.id] = count; - return true; - } - delete animationsToCount[animations.id]; - - // Funcs is needed because an earlier func can try to cascade right away (when no animation for example) and will kill this func and move on to the - // next one (which may not even exist). If we get all funcs before calling any, then we know they are all the func we want. - var funcs = []; - for(i = 0; i < animations.length; i++) { - animation = animations[i]; - funcs.push(getAnimation(animation.id, animation.type)); - } - for(i = 0; i < funcs.length; i++) { - funcs[i](); - } - - return true; - } - - var _refreshing = []; - _action.refreshStart = function(repeaterId) { _refreshing.push(repeaterId); }; - _action.refreshEnd = function() { _refreshing.pop(); }; - - // TODO: [ben] Consider moving this to repeater.js - var _repeatersToRefresh = _action.repeatersToRefresh = []; - var _ignoreAction = function(repeaterId) { - for(var i = 0; i < _refreshing.length; i++) if(_refreshing[i] == repeaterId) return true; - return false; - }; - - var _addRefresh = function(repeaterId) { - if(_repeatersToRefresh.indexOf(repeaterId) == -1) _repeatersToRefresh.push(repeaterId); - }; - - var _getIdToResizeMoveState = function(eventInfo) { - if(!eventInfo.idToResizeMoveState) eventInfo.idToResizeMoveState = {}; - return eventInfo.idToResizeMoveState; - } - - var _queueResizeMove = function (id, type, eventInfo, actionInfo) { - if (type == queueTypes.resize || type == queueTypes.rotate) $ax.public.fn.convertToSingleImage($jobj(id)); - - var idToResizeMoveState = _getIdToResizeMoveState(eventInfo); - if(!idToResizeMoveState[id]) { - idToResizeMoveState[id] = {}; - idToResizeMoveState[id][queueTypes.move] = { queue: [], used: 0 }; - idToResizeMoveState[id][queueTypes.resize] = { queue: [], used: 0 }; - idToResizeMoveState[id][queueTypes.rotate] = { queue: [], used: 0 }; - } - var state = idToResizeMoveState[id]; - - // If this is not a type being queued (no action of it's type waiting already) then if it is an instant, fire right away. - var myOptions = type == queueTypes.resize ? actionInfo : actionInfo.options; - if(!state[type].queue.length && (!myOptions.easing || myOptions.easing == 'none' || !myOptions.duration)) { - var func = type == queueTypes.resize ? _addResize : type == queueTypes.rotate ? _addRotate : _addMove; - func(id, eventInfo, actionInfo, { easing: 'none', duration: 0, stop: { instant: true } }); - return; - } - - // Check other 2 types to see if either is empty, if so, we can't do anything, so just queue it up - var otherType1 = type == queueTypes.move ? queueTypes.resize : queueTypes.move; - var otherType2 = type == queueTypes.rotate ? queueTypes.resize : queueTypes.rotate; - if (!state[otherType1].queue.length || !state[otherType2].queue.length) { - state[type].queue.push({ eventInfo: eventInfo, actionInfo: actionInfo }); - } else { - var duration = myOptions.duration; - var used1 = state[otherType1].used; - var used2 = state[otherType2].used; - - while(state[otherType1].queue.length && state[otherType2].queue.length && duration != 0) { - var other1 = state[otherType1].queue[0]; - var otherOptions1 = otherType1 == queueTypes.resize ? other1.actionInfo : other1.actionInfo.options; - // If queue up action is a non animation, then don't combo it, just queue it and move on - if(!otherOptions1.easing || otherOptions1.easing == 'none' || !otherOptions1.duration) { - func = otherType1 == queueTypes.resize ? _addResize : otherType1 == queueTypes.rotate ? _addRotate : _addMove; - func(id, eventInfo, actionInfo, { easing: 'none', duration: 0, stop: { instant: true } }); - continue; - } - var other2 = state[otherType2].queue[0]; - var otherOptions2 = otherType2 == queueTypes.resize ? other2.actionInfo : other2.actionInfo.options; - // If queue up action is a non animation, then don't combo it, just queue it and move on - if(!otherOptions2.easing || otherOptions2.easing == 'none' || !otherOptions2.duration) { - func = otherType2 == queueTypes.resize ? _addResize : otherType2 == queueTypes.rotate ? _addRotate : _addMove; - func(id, eventInfo, actionInfo, { easing: 'none', duration: 0, stop: { instant: true } }); - continue; - } - - // Other duration is what is left over. When in queue it may be partly finished already - var otherDuration1 = otherOptions1.duration - used1; - var otherDuration2 = otherOptions2.duration - used2; - - var resizeInfo = type == queueTypes.resize ? actionInfo : otherType1 == queueTypes.resize ? other1.actionInfo : other2.actionInfo; - var rotateInfo = type == queueTypes.rotate ? actionInfo : otherType1 == queueTypes.rotate ? other1.actionInfo : other2.actionInfo; - var moveInfo = type == queueTypes.move ? actionInfo : otherType1 == queueTypes.move ? other1.actionInfo : other2.actionInfo; - var options = { easing: moveInfo.options.easing, duration: Math.min(duration, otherDuration1, otherDuration2) }; - // Start for self is whole duration - duration left, end is start plus duration of combo to be queued, length is duration - var stop = { start: myOptions.duration - duration, len: myOptions.duration }; - stop.end = stop.start + options.duration; - // Start for other is used (will be 0 after 1st round), end is start plus length is duration of combo to be queued, length is other duration - var otherStop1 = { start: used1, end: options.duration + used1, len: otherOptions1.duration }; - var otherStop2 = { start: used2, end: options.duration + used2, len: otherOptions2.duration }; - options.stop = type == queueTypes.resize ? stop : otherType1 == queueTypes.resize ? otherStop1 : otherStop2; - options.moveStop = type == queueTypes.move ? stop : otherType1 == queueTypes.move ? otherStop1 : otherStop2; - options.rotateStop = type == queueTypes.rotate ? stop : otherType1 == queueTypes.rotate ? otherStop1 : otherStop2; - - _addResize(id, eventInfo, resizeInfo, options, moveInfo, rotateInfo); - - // Update duration for this animation - duration -= options.duration; - // For others update used and remove from queue if necessary - if(otherDuration1 == options.duration) { - $ax.splice(state[otherType1].queue, 0, 1); - used1 = 0; - } else used1 += options.duration; - - if(otherDuration2 == options.duration) { - $ax.splice(state[otherType2].queue, 0, 1); - used2 = 0; - } else used2 += options.duration; - } - - // Start queue for new type if necessary - if(duration) { - state[type].queue.push({ eventInfo: eventInfo, actionInfo: actionInfo }); - state[type].used = myOptions.duration - duration; - } - - // Update used for others - state[otherType1].used = used1; - state[otherType2].used = used2; - } - }; - - _action.flushAllResizeMoveActions = function (eventInfo) { - var idToResizeMoveState = _getIdToResizeMoveState(eventInfo); - for(var id in idToResizeMoveState) _flushResizeMoveActions(id, idToResizeMoveState); - }; - - var _flushResizeMoveActions = function(id, idToResizeMoveState) { - var state = idToResizeMoveState[id]; - var move = state[queueTypes.move]; - var moveInfo = move.queue[0]; - var resize = state[queueTypes.resize]; - var resizeInfo = resize.queue[0]; - var rotate = state[queueTypes.rotate]; - var rotateInfo = rotate.queue[0]; - while (moveInfo || resizeInfo || rotateInfo) { - var eventInfo = moveInfo ? moveInfo.eventInfo : resizeInfo ? resizeInfo.eventInfo : rotateInfo.eventInfo; - moveInfo = moveInfo && moveInfo.actionInfo; - resizeInfo = resizeInfo && resizeInfo.actionInfo; - rotateInfo = rotateInfo && rotateInfo.actionInfo; - - // Resize is used by default, then rotate - if(resizeInfo) { - // Check for instant resize - if(!resizeInfo.duration || resizeInfo.easing == 'none') { - _addResize(id, resize.queue[0].eventInfo, resizeInfo, { easing: 'none', duration: 0, stop: { instant: true } }); - _updateResizeMoveUsed(id, queueTypes.resize, 0, idToResizeMoveState); - resizeInfo = resize.queue[0]; - continue; - } - - var duration = resizeInfo.duration - resize.used; - if(moveInfo) duration = Math.min(duration, moveInfo.options.duration - move.used); - if(rotateInfo) duration = Math.min(duration, rotateInfo.options.duration - rotate.used); - - var baseOptions = moveInfo ? moveInfo.options : resizeInfo; - var options = { easing: baseOptions.easing, duration: duration }; - - options.stop = { start: resize.used, end: resize.used + duration, len: resizeInfo.duration }; - if(moveInfo) options.moveStop = { start: move.used, end: move.used + duration, len: moveInfo.options.duration }; - if(rotateInfo) options.rotateStop = { start: rotate.used, end: rotate.used + duration, len: rotateInfo.options.duration }; - - _addResize(id, eventInfo, resizeInfo, options, moveInfo, rotateInfo); - - _updateResizeMoveUsed(id, queueTypes.resize, duration, idToResizeMoveState); - resizeInfo = resize.queue[0]; - if(rotateInfo) { - _updateResizeMoveUsed(id, queueTypes.rotate, duration, idToResizeMoveState); - rotateInfo = rotate.queue[0]; - } - if(moveInfo) { - _updateResizeMoveUsed(id, queueTypes.move, duration, idToResizeMoveState); - moveInfo = move.queue[0]; - } - } else if (rotateInfo) { - // Check for instant rotate - if(!rotateInfo.options.duration || rotateInfo.options.easing == 'none') { - _addRotate(id, rotate.queue[0].eventInfo, rotateInfo, { easing: 'none', duration: 0, stop: { instant: true } }); - _updateResizeMoveUsed(id, queueTypes.rotate, 0, idToResizeMoveState); - rotateInfo = rotate.queue[0]; - continue; - } - - duration = rotateInfo.options.duration - rotate.used; - if(moveInfo) duration = Math.min(duration, moveInfo.options.duration - move.used); - - baseOptions = moveInfo ? moveInfo.options : rotateInfo.options; - options = { easing: baseOptions.easing, duration: duration }; - - options.stop = { start: rotate.used, end: rotate.used + duration, len: rotateInfo.options.duration }; - if(moveInfo) options.moveStop = { start: move.used, end: move.used + duration, len: moveInfo.options.duration }; - - _addRotate(id, eventInfo, rotateInfo, options, moveInfo); - - _updateResizeMoveUsed(id, queueTypes.rotate, duration, idToResizeMoveState); - rotateInfo = rotate.queue[0]; - if(moveInfo) { - _updateResizeMoveUsed(id, queueTypes.move, duration, idToResizeMoveState); - moveInfo = move.queue[0]; - } - } else { - if(!moveInfo.options.duration || moveInfo.options.easing == 'none') { - _addMove(id, eventInfo, moveInfo, { easing: 'none', duration: 0, stop: { instant: true } }); - _updateResizeMoveUsed(id, queueTypes.move, 0, idToResizeMoveState); - moveInfo = move.queue[0]; - continue; - } - - duration = moveInfo.options.duration - move.used; - options = { easing: moveInfo.options.easing, duration: duration }; - options.stop = { start: move.used, end: moveInfo.options.duration, len: moveInfo.options.duration }; - _addMove(id, eventInfo, moveInfo, options); - - _updateResizeMoveUsed(id, queueTypes.move, duration, idToResizeMoveState); - moveInfo = move.queue[0]; - } - } - }; - - var _updateResizeMoveUsed = function(id, type, duration, idToResizeMoveState) { - var state = idToResizeMoveState[id][type]; - state.used += duration; - var options = state.queue[0].actionInfo; - if(options.options) options = options.options; - var optionDur = (options.easing && options.easing != 'none' && options.duration) || 0; - if(optionDur <= state.used) { - $ax.splice(state.queue, 0, 1); - state.used = 0; - } - } - - var _dispatchAction = $ax.action.dispatchAction = function(eventInfo, actions, currentIndex) { - currentIndex = currentIndex || 0; - //If no actions, you can bubble - if(currentIndex >= actions.length) return; - //actions are responsible for doing their own dispatching - _actionHandlers[actions[currentIndex].action](eventInfo, actions, currentIndex); - }; - - _actionHandlers.wait = function(eventInfo, actions, index) { - var action = actions[index]; - var infoCopy = $ax.eventCopy(eventInfo); - window.setTimeout(function() { - infoCopy.now = new Date(); - infoCopy.idToResizeMoveState = undefined; - _dispatchAction(infoCopy, actions, index + 1); - _action.flushAllResizeMoveActions(infoCopy); - }, action.waitTime); - }; - - _actionHandlers.expr = function(eventInfo, actions, index) { - var action = actions[index]; - - $ax.expr.evaluateExpr(action.expr, eventInfo); //this should be a block - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.setFunction = _actionHandlers.expr; - - _actionHandlers.linkWindow = function(eventInfo, actions, index) { - linkActionHelper(eventInfo, actions, index); - }; - - _actionHandlers.closeCurrent = function(eventInfo, actions, index) { - $ax.closeWindow(); - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.linkFrame = function(eventInfo, actions, index) { - linkActionHelper(eventInfo, actions, index); - }; - - _actionHandlers.setAdaptiveView = function(eventInfo, actions, index) { - var action = actions[index]; - var view = action.setAdaptiveViewTo; - - if(view) $ax.adaptive.setAdaptiveView(view); - }; - - var linkActionHelper = function(eventInfo, actions, index) { - var action = actions[index]; - eventInfo.link = true; - - if(action.linkType != 'frame') { - var includeVars = _includeVars(action.target, eventInfo); - if(action.target.targetType == "reloadPage") { - $ax.reload(action.target.includeVariables); - } else if(action.target.targetType == "backUrl") { - $ax.back(); - } - - var url = action.target.url; - if(!url && action.target.urlLiteral) { - url = $ax.expr.evaluateExpr(action.target.urlLiteral, eventInfo, true); - } - - if(url) { - let useStartHtml = shouldUseStartHtml(action); - if(useStartHtml) { - //use start.html to load player - url = urlWithStartHtml(url); - //collapse player for popup - if(action.linkType == "popup") url = urlWithCollapseSitemap(url); - } - - //set useGlobalVarNameInUrl to true to use GLOBAL_VAR_NAME in the url, so player knows how to parse it - //without this, we are assuming everything after '#' are global vars - if(action.linkType == "popup") { - $ax.navigate({ - url: url, - target: action.linkType, - includeVariables: includeVars, - popupOptions: action.popup, - useGlobalVarNameInUrl : useStartHtml - }); - } else { - $ax.navigate({ - url: url, - target: action.linkType, - includeVariables: includeVars, - useGlobalVarNameInUrl : useStartHtml - }); - } - } - } else linkFrame(eventInfo, action); - eventInfo.link = false; - - _dispatchAction(eventInfo, actions, index + 1); - }; - - //use start.html will add a player to the prototype - var shouldUseStartHtml = function(linkAction) { - return linkAction.target.targetType == 'page' //only adding player for page, not external links - && (linkAction.linkType == "popup" || linkAction.linkType == "new") //only add for popup and new tabs - && $axure.utils.isInPlayer() //allow user to view without player (maybe useful for user testing) - && !$axure.utils.isShareApp() //share app use special handling on its link, add start.html breaks the handling - } - - var urlWithStartHtml = function(url) { - var pageName = url.substring(0, url.lastIndexOf('.html')); - var pageHash = $axure.utils.setHashStringVar(START_URL_NAME, PAGE_URL_NAME, pageName); - return START_URL_NAME + pageHash; - } - - var urlWithCollapseSitemap = function(url) { - return url + '&' + SITEMAP_COLLAPSE_VAR_NAME + '=' + SITEMAP_COLLAPSE_VALUE; - } - - var _includeVars = function(target, eventInfo) { - if(target.includeVariables) return true; - // If it is a url literal, that is a string literal, that has only 1 sto, that is an item that is a page, include vars. - if(target.urlLiteral) { - var literal = target.urlLiteral; - var sto = literal.stos[0]; - if(literal.exprType == 'stringLiteral' && literal.value.indexOf('[[') == 0 && literal.value.indexOf(']]' == literal.value.length - 2) && literal.stos.length == 1 && sto.sto == 'item' && eventInfo.item) { - var data = $ax.repeater.getData(eventInfo, eventInfo.item.repeater.elementId, eventInfo.item.index, sto.name, 'data'); - if (data && $ax.public.fn.IsPage(data.type)) return true; - } - } - return false; - }; - - var linkFrame = function(eventInfo, action) { - for(var i = 0; i < action.framesToTargets.length; i++) { - var framePath = action.framesToTargets[i].framePath; - var target = action.framesToTargets[i].target; - var includeVars = _includeVars(target, eventInfo); - - var url = target.url; - if(!url && target.urlLiteral) { - url = $ax.expr.evaluateExpr(target.urlLiteral, eventInfo, true); - } - - var id = $ax.getElementIdsFromPath(framePath, eventInfo)[0]; - if(id) $ax('#' + $ax.INPUT(id)).openLink(url, includeVars); - } - }; - - var _repeatPanelMap = {}; - - _actionHandlers.setPanelState = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.panelsToStates.length; i++) { - var panelToState = action.panelsToStates[i]; - var stateInfo = panelToState.stateInfo; - var elementIds = $ax.getElementIdsFromPath(panelToState.panelPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - // Need new scope for elementId and info - (function(elementId, stateInfo) { - _addAnimation(elementId, queueTypes.setState, function() { - var stateNumber = stateInfo.stateNumber; - if(stateInfo.setStateType == "value") { - var oldTarget = eventInfo.targetElement; - eventInfo.targetElement = elementId; - var stateName = $ax.expr.evaluateExpr(stateInfo.stateValue, eventInfo); - eventInfo.targetElement = oldTarget; - - // Try for state name first - var states = $ax.getObjectFromElementId(elementId).diagrams; - var stateNameFound = false; - for(var k = 0; k < states.length; k++) { - if(states[k].label == stateName) { - stateNumber = k + 1; - stateNameFound = true; - } - } - - // Now check for index - if(!stateNameFound) { - stateNumber = Number(stateName); - var panelCount = $('#' + elementId).children().length; - - // Make sure number is not NaN, is in range, and is a whole number. - // Wasn't a state name or number, so return - if(isNaN(stateNumber) || stateNumber <= 0 || stateNumber > panelCount || Math.round(stateNumber) != stateNumber) return _fireAnimationFromQueue(elementId, queueTypes.setState); - } - } else if(stateInfo.setStateType == 'next' || stateInfo.setStateType == 'previous') { - var info = $ax.deepCopy(stateInfo); - var repeat = info.repeat; - - // Only map it, if repeat exists. - if(typeof (repeat) == 'number') _repeatPanelMap[elementId] = info; - return _progessPanelState(elementId, info, info.repeatSkipFirst); - } - delete _repeatPanelMap[elementId]; - - // If setting to current (to stop repeat) break here - if(stateInfo.setStateType == 'current') return _fireAnimationFromQueue(elementId, queueTypes.setState); - - $ax('#' + elementId).SetPanelState(stateNumber, stateInfo.options, stateInfo.showWhenSet); - }); - })(elementId, stateInfo); - } - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - var _progessPanelState = function(id, info, skipFirst) { - var direction = info.setStateType; - var loop = info.loop; - var repeat = info.repeat; - var options = info.options; - - var hasRepeat = typeof (repeat) == 'number'; - var currentStateId = $ax.visibility.GetPanelState(id); - var stateNumber = ''; - if(currentStateId != '') { - currentStateId = $ax.repeater.getScriptIdFromElementId(currentStateId); - var currentStateNumber = Number(currentStateId.substr(currentStateId.indexOf('state') + 5)); - if(direction == "next") { - stateNumber = currentStateNumber + 2; - - if(stateNumber > $ax.visibility.GetPanelStateCount(id)) { - if(loop) stateNumber = 1; - else { - delete _repeatPanelMap[id]; - return _fireAnimationFromQueue(id, queueTypes.setState); - } - } - } else if(direction == "previous") { - stateNumber = currentStateNumber; - if(stateNumber <= 0) { - if(loop) stateNumber = $ax.visibility.GetPanelStateCount(id); - else { - delete _repeatPanelMap[id]; - return _fireAnimationFromQueue(id, queueTypes.setState); - } - } - } - - if(hasRepeat && _repeatPanelMap[id] != info) return _fireAnimationFromQueue(id, queueTypes.setState); - - if (!skipFirst) $ax('#' + id).SetPanelState(stateNumber, options, info.showWhenSet); - else _fireAnimationFromQueue(id, queueTypes.setState); - - if(hasRepeat) { - var animate = options && options.animateIn; - if(animate && animate.easing && animate.easing != 'none' && animate.duration > repeat) repeat = animate.duration; - animate = options && options.animateOut; - if(animate && animate.easing && animate.easing != 'none' && animate.duration > repeat) repeat = animate.duration; - - window.setTimeout(function() { - // Either new repeat, or no repeat anymore. - if(_repeatPanelMap[id] != info) return; - _addAnimation(id, queueTypes.setState, function() { - _progessPanelState(id, info, false); - }); - }, repeat); - } else delete _repeatPanelMap[id]; - } - }; - - _actionHandlers.fadeWidget = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.objectsToFades.length; i++) { - var fadeInfo = action.objectsToFades[i].fadeInfo; - var elementIds = $ax.getElementIdsFromPath(action.objectsToFades[i].objectPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - // Need new scope for elementId and info - (function(elementId, fadeInfo) { - _addAnimation(elementId, queueTypes.fade, function() { - if(fadeInfo.fadeType == "hide") { - $ax('#' + elementId).hide(fadeInfo.options); - } else if(fadeInfo.fadeType == "show") { - $ax('#' + elementId).show(fadeInfo.options, eventInfo); - } else if(fadeInfo.fadeType == "toggle") { - $ax('#' + elementId).toggleVisibility(fadeInfo.options); - } - }); - })(elementId, fadeInfo); - } - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.setOpacity = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.objectsToSetOpacity.length; i++) { - var opacityInfo = action.objectsToSetOpacity[i].opacityInfo; - var elementIds = $ax.getElementIdsFromPath(action.objectsToSetOpacity[i].objectPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - - (function(elementId, opacityInfo) { - _addAnimation(elementId, queueTypes.fade, function () { - var oldTarget = eventInfo.targetElement; - eventInfo.targetElement = elementId; - var opacity = $ax.expr.evaluateExpr(opacityInfo.opacity, eventInfo); - eventInfo.targetElement = oldTarget; - opacity = Math.min(100, Math.max(0, opacity)); - $ax('#' + elementId).setOpacity(opacity/100, opacityInfo.easing, opacityInfo.duration); - }) - })(elementId, opacityInfo); - } - } - - _dispatchAction(eventInfo, actions, index + 1); - } - - _actionHandlers.moveWidget = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.objectsToMoves.length; i++) { - var moveInfo = action.objectsToMoves[i].moveInfo; - var elementIds = $ax.getElementIdsFromPath(action.objectsToMoves[i].objectPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - _queueResizeMove(elementId, queueTypes.move, eventInfo, moveInfo); - //_addMove(eventInfo, elementId, moveInfo, eventInfo.dragInfo); - } - } - _dispatchAction(eventInfo, actions, index + 1); - }; - - //var _compoundChildrenShallow = function (id) { - // var deep = []; - // var children = $ax('#' + id).getChildren()[0].children; - // var piecePrefix = id + 'p'; - - // for (var i = 0; i < children.length; i++) { - // if(children[i].substring(0, id.length + 1) == piecePrefix) { - // deep.push(children[i]); - // } - // } - // return deep; - //}; - - var _addMove = function (elementId, eventInfo, moveInfo, optionsOverride) { - var eventInfoCopy = $ax.eventCopy(eventInfo); - var idToResizeMoveState = _getIdToResizeMoveState(eventInfoCopy); - eventInfoCopy.targetElement = elementId; - - var options = $ax.deepCopy(moveInfo.options); - options.easing = optionsOverride.easing; - options.duration = optionsOverride.duration; - options.dragInfo = eventInfo.dragInfo; - - if($ax.public.fn.IsLayer($obj(elementId).type)) { - var childrenIds = $ax.public.fn.getLayerChildrenDeep(elementId, true); - if(childrenIds.length == 0) return; - - var animations = []; - - // Get move delta once, then apply to all children - animations.push({ - id: elementId, - type: queueTypes.move, - func: function () { - var layerInfo = $ax('#' + elementId).offsetBoundingRect(); - //var layerInfo = $ax.public.fn.getWidgetBoundingRect(elementId); - var deltaLoc = _getMoveLoc(elementId, moveInfo, eventInfoCopy, optionsOverride.stop, idToResizeMoveState[elementId], options, layerInfo); -// $ax.event.raiseSyntheticEvent(elementId, "onMove"); - $ax.visibility.pushContainer(elementId, false); - - options.onComplete = function () { - _fireAnimationFromQueue(elementId, queueTypes.move); - $ax.visibility.popContainer(elementId, false); - }; - - $ax('#' + elementId).moveBy(deltaLoc.x, deltaLoc.y, options); - } - }); - - //for(var i = 0; i < childrenIds.length; i++) { - // (function(childId) { - // animations.push({ - // id: childId, - // type: queueTypes.move, - // func: function () { - // // Nop, while trying to move as container - // //$ax.event.raiseSyntheticEvent(childId, "onMove"); - // //if($ax.public.fn.IsLayer($obj(childId).type)) _fireAnimationFromQueue(childId, queueTypes.move); - // //else $ax('#' + childId).moveBy(deltaLoc.x, deltaLoc.y, moveInfo.options); - // } - // }); - // })(childrenIds[i]); - //} - _addAnimations(animations); - } else { - _addAnimation(elementId, queueTypes.move, function() { - var loc = _getMoveLoc(elementId, moveInfo, eventInfoCopy, optionsOverride.stop, idToResizeMoveState[elementId], options); - -// $ax.event.raiseSyntheticEvent(elementId, "onMove"); - if(loc.moveTo) $ax('#' + elementId).moveTo(loc.x, loc.y, options); - else $ax('#' + elementId).moveBy(loc.x, loc.y, options); - }); - } - }; - - var _moveSingleWidget = function (elementId, delta, options, onComplete) { - if(!delta.x && !delta.y) { - $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.move); - if (onComplete) onComplete(); - return; - } - var fixedInfo = $ax.dynamicPanelManager.getFixedInfo(elementId); - var xProp = 'left'; - var xDiff = '+='; - if(fixedInfo) { - if(fixedInfo.horizontal == 'right') { - xProp = 'right'; - xDiff = '-='; - } else if(fixedInfo.horizontal == 'center') { - xProp = 'margin-left'; - } - } - var yProp = 'top'; - var yDiff = '+='; - if(fixedInfo) { - if(fixedInfo.vertical == 'bottom') { - yProp = 'bottom'; - yDiff = '-='; - } else if(fixedInfo.vertical == 'middle') { - yProp = 'margin-top'; - } - } - - var css = {}; - css[xProp] = xDiff + delta.x; - css[yProp] = yDiff + delta.y; - - $ax.visibility.moveMovedLocation(elementId, delta.x, delta.y); - - var moveInfo = $ax.move.PrepareForMove(elementId, delta.x, delta.y,false, options); - $jobjAll(elementId).animate(css, { - duration: options.duration, - easing: options.easing, - queue: false, - complete: function () { - if(onComplete) onComplete(); - if(moveInfo.rootLayer) $ax.visibility.popContainer(moveInfo.rootLayer, false); - $ax.dynamicPanelManager.fitParentPanel(elementId); - $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.move); - } - }); - } - - var _getMoveLoc = function (elementId, moveInfo, eventInfoCopy, stopInfo, comboState, options, layerInfo) { - var moveTo = false; - var moveWithThis = false; - var xValue = 0; - var yValue = 0; - var moveResult = comboState.moveResult; - var widgetDragInfo = eventInfoCopy.dragInfo; - var jobj = $jobj(elementId); - - var startX; - var startY; - - switch(moveInfo.moveType) { - case "location": - // toRatio is ignoring anything before start since that has already taken effect we just know whe have from start to len to finish - // getting to the location we want to get to. - var toRatio = stopInfo.instant ? 1 : (stopInfo.end - stopInfo.start) / (stopInfo.len - stopInfo.start); - - // If result already caluculated, don't recalculate again, other calculate and save - if (moveResult) { - xValue = moveResult.x; - yValue = moveResult.y; - } else { - comboState.moveResult = moveResult = { x: $ax.expr.evaluateExpr(moveInfo.xValue, eventInfoCopy), y: $ax.expr.evaluateExpr(moveInfo.yValue, eventInfoCopy) }; - xValue = moveResult.x; - yValue = moveResult.y; - } - // If this is final stop for this move, then clear out the result so next move won't use it - if(stopInfo.instant || stopInfo.end == stopInfo.len) comboState.moveResult = undefined; - - if (layerInfo) { - startX = layerInfo.left; - startY = layerInfo.top; - //} else if ($ax.public.fn.isCompoundVectorHtml(jobj[0])) { - // var dimensions = $ax.public.fn.compoundWidgetDimensions(jobj); - // startX = dimensions.left; - // startY = dimensions.top; - } else { - var offsetLocation = $ax('#' + elementId).offsetLocation(); - startX = offsetLocation.left; - startY = offsetLocation.top; - //startX = $ax('#' + elementId).locRelativeIgnoreLayer(false); - //startY = $ax('#' + elementId).locRelativeIgnoreLayer(true); - if(jobj.css('position') == 'fixed') { - startX -= $(window).scrollLeft(); - startY -= $(window).scrollTop(); - } - } - - xValue = xValue == '' ? 0 : (xValue - startX) * toRatio; - yValue = yValue == '' ? 0 : (yValue - startY) * toRatio; - - break; - case "delta": - var ratio = stopInfo.instant ? 1 : (stopInfo.end - stopInfo.start) / stopInfo.len; - - // See case location above - if(moveResult) { - xValue = moveResult.x * ratio; - yValue = moveResult.y * ratio; - } else { - comboState.moveResult = moveResult = { x: $ax.expr.evaluateExpr(moveInfo.xValue, eventInfoCopy), y: $ax.expr.evaluateExpr(moveInfo.yValue, eventInfoCopy) }; - xValue = moveResult.x * ratio; - yValue = moveResult.y * ratio; - } - if (stopInfo.instant || stopInfo.end == stopInfo.len) comboState.moveResult = undefined; - - break; - case "drag": - xValue = widgetDragInfo.xDelta; - yValue = widgetDragInfo.yDelta; - break; - case "dragX": - xValue = widgetDragInfo.xDelta; - yValue = 0; - break; - case "dragY": - xValue = 0; - yValue = widgetDragInfo.yDelta; - break; - case "locationBeforeDrag": - var location = widgetDragInfo.movedWidgets[eventInfoCopy.targetElement]; - if (location) { - var axObj = $ax('#' + eventInfoCopy.targetElement); - //This may require using the css value - var viewportLocation = axObj.viewportLocation(); - xValue = location.x - viewportLocation.left; - yValue = location.y - viewportLocation.top; - //xValue = location.x - axObj.left(); - //yValue = location.y - axObj.top(); - } else { - _fireAnimationFromQueue(eventInfoCopy.srcElement, queueTypes.move); - return { x: 0, y: 0 }; - } - //moveTo = true; - break; - case "withThis": - moveWithThis = true; - var widgetMoveInfo = $ax.move.GetWidgetMoveInfo(); - var srcElementId = $ax.getElementIdsFromEventAndScriptId(eventInfoCopy, eventInfoCopy.srcElement)[0]; - var delta = widgetMoveInfo[srcElementId]; - options.easing = delta.options.easing; - options.duration = delta.options.duration; - xValue = delta.x; - yValue = delta.y; - break; - } - - if (options && options.boundaryExpr) { - //$ax.public.fn.removeCompound(jobj); - - //if(jobj.css('position') == 'fixed') { - // //swap page coordinates with fixed coordinates - // options.boundaryExpr.leftExpr.value = options.boundaryExpr.leftExpr.value.replace('.top', '.topfixed').replace('.left', '.leftfixed').replace('.bottom', '.bottomfixed').replace('.right', '.rightfixed'); - // options.boundaryExpr.leftExpr.stos[0].leftSTO.prop = options.boundaryExpr.leftExpr.stos[0].leftSTO.prop + 'fixed'; - // options.boundaryStos.boundaryScope.direcval0.value = options.boundaryStos.boundaryScope.direcval0.value.replace('.top', '.topfixed').replace('.left', '.leftfixed').replace('.bottom', '.bottomfixed').replace('.right', '.rightfixed'); - // options.boundaryStos.boundaryScope.direcval0.stos[0].leftSTO.prop = options.boundaryStos.boundaryScope.direcval0.stos[0].leftSTO.prop + 'fixed'; - //} - - if(moveWithThis && (xValue || yValue)) { - _updateLeftExprVariable(options.boundaryExpr, xValue.toString(), yValue.toString()); - } - - if(!$ax.expr.evaluateExpr(options.boundaryExpr, eventInfoCopy)) { - var boundaryStoInfo = options.boundaryStos; - if(boundaryStoInfo) { - if(moveWithThis) { - var stoScopes = boundaryStoInfo.boundaryScope; - if(stoScopes) { - for(var s in stoScopes) { - var boundaryScope = stoScopes[s]; - if(!boundaryScope.localVariables) continue; - - if(boundaryScope.localVariables.withx) boundaryScope.localVariables.withx.value = xValue.toString(); - if(boundaryScope.localVariables.withy) boundaryScope.localVariables.withy.value = yValue.toString(); - } - } - } - - if(layerInfo) { - startX = layerInfo.left; - startY = layerInfo.top; - } else { - offsetLocation = $ax('#' + elementId).offsetLocation(); - startX = offsetLocation.left; - startY = offsetLocation.top; - //startX = $ax('#' + elementId).locRelativeIgnoreLayer(false); - //startY = $ax('#' + elementId).locRelativeIgnoreLayer(true); - if(jobj.css('position') == 'fixed') { - startX -= $(window).scrollLeft(); - startY -= $(window).scrollTop(); - } - } - - if(boundaryStoInfo.ySto) { - var currentTop = layerInfo ? layerInfo.top : startY; - var newTop = $ax.evaluateSTO(boundaryStoInfo.ySto, boundaryStoInfo.boundaryScope, eventInfoCopy); - if(moveTo) yValue = newTop; - else yValue = newTop - currentTop; - } - - if(boundaryStoInfo.xSto) { - var currentLeft = layerInfo ? layerInfo.left : startX; - var newLeft = $ax.evaluateSTO(boundaryStoInfo.xSto, boundaryStoInfo.boundaryScope, eventInfoCopy); - if(moveTo) xValue = newLeft; - else xValue = newLeft - currentLeft; - } - } - } - - //$ax.public.fn.restoreCompound(jobj); - } - - return { x: Number(xValue), y: Number(yValue), moveTo: moveTo }; - }; - - //we will have something like [[Target.right + withX]] for leftExpr, and this function set the value of withX - var _updateLeftExprVariable = function (exprTree, xValue, yValue) { - if(exprTree.leftExpr && !exprTree.leftExpr.op) { - var localVars = exprTree.leftExpr.localVariables; - if(localVars) { - if(localVars.withx) localVars.withx.value = xValue; - if(localVars.withy) localVars.withy.value = yValue; - } - } - - //traversal - if(exprTree.op) { - if(exprTree.leftExpr) _updateLeftExprVariable(exprTree.leftExpr, xValue, yValue); - if(exprTree.rightExpr) _updateLeftExprVariable(exprTree.rightExpr, xValue, yValue); - } - } - - var widgetRotationFilter = [ - $ax.constants.IMAGE_BOX_TYPE, $ax.constants.IMAGE_MAP_REGION_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE, - $ax.constants.VECTOR_SHAPE_TYPE, $ax.constants.VERTICAL_LINE_TYPE, $ax.constants.HORIZONTAL_LINE_TYPE - ]; - _actionHandlers.rotateWidget = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.objectsToRotate.length; i++) { - var rotateInfo = action.objectsToRotate[i].rotateInfo; - var elementIds = $ax.getElementIdsFromPath(action.objectsToRotate[i].objectPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - _queueResizeMove(elementId, queueTypes.rotate, eventInfo, rotateInfo); - } - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - var _addRotate = function (elementId, eventInfo, rotateInfo, options, moveInfo) { - var idToResizeMoveState = _getIdToResizeMoveState(eventInfo); - rotateInfo = $ax.deepCopy(rotateInfo); - rotateInfo.options.easing = options.easing; - rotateInfo.options.duration = options.duration; - - var eventInfoCopy = $ax.eventCopy(eventInfo); - eventInfoCopy.targetElement = elementId; - - //calculate degree value at start of animation - var rotateDegree; - var offset = {}; - var eval = function(boundingRect) { - rotateDegree = parseFloat($ax.expr.evaluateExpr(rotateInfo.degree, eventInfoCopy)); - offset.x = Number($ax.expr.evaluateExpr(rotateInfo.offsetX, eventInfoCopy)); - offset.y = Number($ax.expr.evaluateExpr(rotateInfo.offsetY, eventInfoCopy)); - if(!rotateInfo.options.clockwise) rotateDegree = -rotateDegree; - - _updateOffset(offset, rotateInfo.anchor, boundingRect); - } - - if(moveInfo) { - var moveOptions = { dragInfo: eventInfoCopy.dragInfo, duration: options.duration, easing: options.easing, boundaryExpr: moveInfo.options.boundaryExpr, boundaryStos: moveInfo.options.boundaryStos }; - } - - var obj = $obj(elementId); - - if($ax.public.fn.IsLayer(obj.type)) { - var childrenIds = $ax.public.fn.getLayerChildrenDeep(elementId, true, true); - if(childrenIds.length == 0) return; - - var animations = []; - //get center point of the group, and degree delta - var centerPoint, degreeDelta, moveDelta; - animations.push({ - id: elementId, - type: queueTypes.rotate, - func: function () { - var boundingRect = $ax('#' + elementId).offsetBoundingRect(); - //var boundingRect = $axure.fn.getWidgetBoundingRect(elementId); - eval(boundingRect); - centerPoint = boundingRect.centerPoint; - centerPoint.x += offset.x; - centerPoint.y += offset.y; - degreeDelta = _initRotateLayer(elementId, rotateInfo, rotateDegree, options, options.stop); - _fireAnimationFromQueue(elementId, queueTypes.rotate); - - moveDelta = { x: 0, y: 0 }; - if (moveInfo) { - moveDelta = _getMoveLoc(elementId, moveInfo, eventInfoCopy, options.moveStop, idToResizeMoveState[elementId], moveOptions, boundingRect); - if (moveDelta.moveTo) { - moveDelta.x -= $ax.getNumFromPx($jobj(elementId).css('left')); - moveDelta.y -= $ax.getNumFromPx($jobj(elementId).css('top')); - } - $ax.event.raiseSyntheticEvent(elementId, 'onMove'); - } - } - }); - - for(var idIndex = 0; idIndex < childrenIds.length; idIndex++) { - var childId = childrenIds[idIndex]; - (function(id) { - var childObj = $obj(id); - var rotate = $.inArray(childObj.type, widgetRotationFilter) != -1; - - var isLayer = $ax.public.fn.IsLayer(childObj.type); - animations.push({ - id: id, - type: queueTypes.rotate, - func: function() { - $ax.event.raiseSyntheticEvent(id, "onRotate"); - if(isLayer) _fireAnimationFromQueue(id, queueTypes.rotate); - else $ax('#' + id).circularMoveAndRotate(degreeDelta, options, centerPoint.x, centerPoint.y, rotate, moveDelta); - } - }); - if(!isLayer) animations.push({ id: id, type: queueTypes.move, func: function() {} }); - })(childId); - } - - _addAnimations(animations); - } else { - animations = []; - animations.push({ - id: elementId, - type: queueTypes.rotate, - func: function () { - var jobj = $jobj(elementId); - var unrotatedDim = { width: $ax.getNumFromPx(jobj.css('width')), height: $ax.getNumFromPx(jobj.css('height')) }; - eval(unrotatedDim); - var delta = { x: 0, y: 0 }; - if(moveInfo) { - delta = _getMoveLoc(elementId, moveInfo, eventInfoCopy, options.moveStop, idToResizeMoveState[elementId], moveOptions); - if(delta.moveTo) { - delta.x -= $ax.getNumFromPx($jobj(elementId).css('left')); - delta.y -= $ax.getNumFromPx($jobj(elementId).css('top')); - } - } - - $ax.event.raiseSyntheticEvent(elementId, 'onRotate'); - if(offset.x == 0 && offset.y == 0) _rotateSingle(elementId, rotateDegree, rotateInfo.rotateType == 'location', delta, options, options.stop, true); - else _rotateSingleOffset(elementId, rotateDegree, rotateInfo.rotateType == 'location', delta, { x: offset.x, y: offset.y }, options, options.stop); - if(moveInfo) $ax.event.raiseSyntheticEvent(elementId, 'onMove'); - } - }); - animations.push({ id: elementId, type: queueTypes.move, func: function () { } }); - - _addAnimations(animations); - } - } - - var _updateOffset = function(offset, anchor, boundingRect) { - if (anchor.indexOf('left') != -1) offset.x -= boundingRect.width / 2; - if (anchor.indexOf('right') != -1) offset.x += boundingRect.width / 2; - if (anchor.indexOf('top') != -1) offset.y -= boundingRect.height / 2; - if (anchor.indexOf('bottom') != -1) offset.y += boundingRect.height / 2; - } - - var _rotateSingle = function(elementId, rotateDegree, rotateTo, delta, options, stop, handleMove) { - var degreeDelta = _applyRotateStop(rotateDegree, $ax.move.getRotationDegree(elementId), rotateTo, stop); - $ax('#' + elementId).rotate(degreeDelta, options.easing, options.duration, false, true); - if(handleMove) { - if (delta.x || delta.y) _moveSingleWidget(elementId, delta, options); - else $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.move); - } - }; - - var _rotateSingleOffset = function (elementId, rotateDegree, rotateTo, delta, offset, options, stop, resizeOffset) { - var obj = $obj(elementId); - var currRotation = $ax.move.getRotationDegree(elementId); - - // Need to fix offset. Want to to stay same place on widget after rotation, so need to take the offset and rotate it to where it should be. - if(currRotation) { - offset = $axure.fn.getPointAfterRotate(currRotation, offset, { x: 0, y: 0 }); - } - - var degreeDelta = _applyRotateStop(rotateDegree, currRotation, rotateTo, stop); - var widgetCenter = $ax('#' + elementId).offsetBoundingRect().centerPoint; - //var widgetCenter = $axure.fn.getWidgetBoundingRect(elementId).centerPoint; - - var rotate = $.inArray(obj.type, widgetRotationFilter) != -1; - $ax('#' + elementId).circularMoveAndRotate(degreeDelta, options, widgetCenter.x + offset.x, widgetCenter.y + offset.y, rotate, delta, resizeOffset); - } - - var _applyRotateStop = function(rotateDegree, currRotation, to, stop) { - var degreeDelta; - var ratio; - if(to) { - degreeDelta = rotateDegree - currRotation; - ratio = stop.instant ? 1 : (stop.end - stop.start) / (stop.len - stop.start); - } else { - degreeDelta = rotateDegree; - ratio = stop.instant ? 1 : (stop.end - stop.start) / stop.len; - } - - return degreeDelta * ratio; - } - - - var _initRotateLayer = function(elementId, rotateInfo, rotateDegree, options, stop) { - var layerDegree = $jobj(elementId).data('layerDegree'); - if (layerDegree === undefined) layerDegree = 0; - else layerDegree = parseFloat(layerDegree); - - var to = rotateInfo.rotateType == 'location'; - var newDegree = to ? rotateDegree : layerDegree + rotateDegree; - var degreeDelta = newDegree - layerDegree; - - var ratio = stop.instant ? 1 : (stop.end - stop.start) / (stop.len - stop.start); - degreeDelta *= ratio; - - $jobj(elementId).data('layerDegree', newDegree); - $ax.event.raiseSyntheticEvent(elementId, "onRotate"); - - return degreeDelta; - } - - _actionHandlers.setWidgetSize = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.objectsToResize.length; i++) { - var resizeInfo = action.objectsToResize[i].sizeInfo; - var objPath = action.objectsToResize[i].objectPath; - if(objPath == 'thisItem') { - var thisId = eventInfo.srcElement; - var repeaterId = $ax.getParentRepeaterFromElementId(thisId); - var itemId = $ax.repeater.getItemIdFromElementId(thisId); - var currSize = $ax.repeater.getItemSize(repeaterId, itemId); - var newSize = _getSizeFromInfo(resizeInfo, eventInfo, currSize.width, currSize.height); - $ax.repeater.setItemSize(repeaterId, itemId, newSize.width, newSize.height); - - continue; - } - - var elementIds = $ax.getElementIdsFromPath(objPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - _queueResizeMove(elementId, queueTypes.resize, eventInfo, resizeInfo); - //_addResize(elementId, resizeInfo); - } - } - _dispatchAction(eventInfo, actions, index + 1); - }; - - // Move info undefined unless this move/resize actions are being merged - var _addResize = function(elementId, eventInfo, resizeInfo, options, moveInfo, rotateInfo) { - var axObject = $obj(elementId); - resizeInfo = $ax.deepCopy(resizeInfo); - resizeInfo.easing = options.easing; - resizeInfo.duration = options.duration; - - var eventInfoCopy = $ax.eventCopy(eventInfo); - eventInfoCopy.targetElement = elementId; - - var moves = moveInfo || resizeInfo.anchor != "top left" || ($ax.public.fn.IsDynamicPanel(axObject.type) && - ((axObject.fixedHorizontal && axObject.fixedHorizontal == 'center') || (axObject.fixedVertical && axObject.fixedVertical == 'middle'))) || - (rotateInfo && (rotateInfo.offsetX || rotateInfo.offsetY)); - - if(moveInfo) { - var moveOptions = { dragInfo: eventInfoCopy.dragInfo, duration: options.duration, easing: options.easing, boundaryExpr: moveInfo.options.boundaryExpr, boundaryStos: moveInfo.options.boundaryStos }; - } - - var idToResizeMoveState = _getIdToResizeMoveState(eventInfoCopy); - - var animations = []; - if($ax.public.fn.IsLayer(axObject.type)) { - moves = true; // Assume widgets will move will layer, even though not all widgets may move - var childrenIds = $ax.public.fn.getLayerChildrenDeep(elementId, true, true); - if(childrenIds.length === 0) return; - // Need to wait to calculate new size, until time to animate, but animates are in separate queues - // best option seems to be to calculate in a "animate" for the layer itself and all children will use that. - // May just have to be redundant if this doesn't work well. - - var boundingRect, widthChangedPercent, heightChangedPercent, unchanged, deltaLoc, degreeDelta, resizeOffset; - animations.push({ - id: elementId, - type: queueTypes.resize, - func: function () { - $ax.visibility.pushContainer(elementId, false); - boundingRect = $ax('#' + elementId).offsetBoundingRect(); - //boundingRect = $ax.public.fn.getWidgetBoundingRect(elementId); - var size = _getSizeFromInfo(resizeInfo, eventInfoCopy, boundingRect.width, boundingRect.height, elementId); - deltaLoc = { x: 0, y: 0 }; - - var stop = options.stop; - var ratio = stop.instant ? 1 : (stop.end - stop.start) / (stop.len - stop.start); - widthChangedPercent = Math.round(size.width - boundingRect.width) / boundingRect.width * ratio; - heightChangedPercent = Math.round(size.height - boundingRect.height) / boundingRect.height * ratio; - resizeOffset = _applyAnchorToResizeOffset(widthChangedPercent * boundingRect.width, heightChangedPercent * boundingRect.height, resizeInfo.anchor); - if(stop.instant || stop.end == stop.len) idToResizeMoveState[elementId].resizeResult = undefined; - - unchanged = widthChangedPercent === 0 && heightChangedPercent === 0; - $ax.event.raiseSyntheticEvent(elementId, 'onResize'); - _fireAnimationFromQueue(elementId, queueTypes.resize); - } - }); - - if(moveInfo) animations.push({ - id: elementId, - type: queueTypes.move, - func: function() { - deltaLoc = _getMoveLoc(elementId, moveInfo, eventInfoCopy, options.moveStop, idToResizeMoveState[elementId], moveOptions, boundingRect); - $ax.visibility.pushContainer(elementId, false); - _fireAnimationFromQueue(elementId, queueTypes.move); - $ax.event.raiseSyntheticEvent(elementId, 'onMove'); - } - }); - if (rotateInfo) animations.push({ - id: elementId, - type: queueTypes.rotate, - func: function () { - resizeOffset = _applyAnchorToResizeOffset(widthChangedPercent * boundingRect.width, heightChangedPercent * boundingRect.height, resizeInfo.anchor); - var rotateDegree = parseFloat($ax.expr.evaluateExpr(rotateInfo.degree, eventInfoCopy)); - degreeDelta = _initRotateLayer(elementId, rotateInfo, rotateDegree, options, options.rotateStop); - _fireAnimationFromQueue(elementId, queueTypes.rotate); - $ax.event.raiseSyntheticEvent(elementId, 'onRotate'); - } - }); - - var completeCount = childrenIds.length*2; // Because there is a resize and move complete, it needs to be doubled - for(var idIndex = 0; idIndex < childrenIds.length; idIndex++) { - // Need to use scoping trick here to make sure childId doesn't change on next loop - (function(childId) { - //use ax obj to get width and height, jquery css give us the value without border - var isLayer = $ax.public.fn.IsLayer($obj(childId).type); - var rotate = $.inArray($obj(childId).type, widgetRotationFilter) != -1; - animations.push({ - id: childId, - type: queueTypes.resize, - func: function() { - //$ax.event.raiseSyntheticEvent(childId, 'onResize'); - if(isLayer) { - completeCount -= 2; - _fireAnimationFromQueue(childId, queueTypes.resize); - $ax.event.raiseSyntheticEvent(childId, 'onResize'); - } else { - var currDeltaLoc = { x: deltaLoc.x, y: deltaLoc.y }; - var resizeDeltaMove = { x: 0, y: 0 }; - var css = _getCssForResizingLayerChild(childId, resizeInfo.anchor, boundingRect, widthChangedPercent, heightChangedPercent, resizeDeltaMove); - var onComplete = function() { - if(--completeCount == 0) $ax.visibility.popContainer(elementId, false); - }; - $ax('#' + childId).resize(css, resizeInfo, true, moves, onComplete); - if(rotateInfo) { - var offset = { x: Number($ax.expr.evaluateExpr(rotateInfo.offsetX, eventInfoCopy)), y: Number($ax.expr.evaluateExpr(rotateInfo.offsetY, eventInfo)) }; - _updateOffset(offset, resizeInfo.anchor, boundingRect); - var centerPoint = { x: boundingRect.centerPoint.x + offset.x, y: boundingRect.centerPoint.y + offset.y }; - $ax('#' + childId).circularMoveAndRotate(degreeDelta, options, centerPoint.x, centerPoint.y, rotate, currDeltaLoc, resizeOffset, resizeDeltaMove, onComplete); - } else { - currDeltaLoc.x += resizeDeltaMove.x; - currDeltaLoc.y += resizeDeltaMove.y; - _moveSingleWidget(childId, currDeltaLoc, options, onComplete); - } - } - } - }); - if(!isLayer) animations.push({ id: childId, type: queueTypes.move, func: function () {} }); - if(!isLayer && rotateInfo) animations.push({ id: childId, type: queueTypes.rotate, func: function () {} }); - })(childrenIds[idIndex]); - } - } else { - // Not func, obj with func - animations.push({ - id: elementId, - type: queueTypes.resize, - func: function() { - //textarea can be resized manully by the user, but doesn't update div size yet, so doing this for now. - //alternatively axquery get for size can account for this - - var sizeId = $ax.public.fn.IsTextArea(axObject.type) ? $jobj(elementId).children('textarea').attr('id') : elementId; - var oldSize = $ax('#' + sizeId).size(); - var oldWidth = oldSize.width; - var oldHeight = oldSize.height; - - var stop = options.stop; - var ratio = stop.instant ? 1 : (stop.end - stop.start) / (stop.len - stop.start); - - var size = _getSizeFromInfo(resizeInfo, eventInfoCopy, oldWidth, oldHeight, elementId); - var newWidth = size.width; - var newHeight = size.height; - var deltaWidth = Math.round(newWidth - oldWidth) * ratio; - var deltaHeight = Math.round(newHeight - oldHeight) * ratio; - newWidth = oldWidth + deltaWidth; - newHeight = oldHeight + deltaHeight; - - var delta = { x: 0, y: 0 }; - if(moveInfo) { - delta = _getMoveLoc(elementId, moveInfo, eventInfoCopy, options.moveStop, idToResizeMoveState[elementId], moveOptions); - if (delta.moveTo) { - delta.x -= $ax.getNumFromPx($jobj(elementId).css('left')); - delta.y -= $ax.getNumFromPx($jobj(elementId).css('top')); - } - } - - var rotateHandlesMove = false; - var offset = { x: 0, y: 0 }; - if(rotateInfo) { - offset.x = Number($ax.expr.evaluateExpr(rotateInfo.offsetX, eventInfoCopy)); - offset.y = Number($ax.expr.evaluateExpr(rotateInfo.offsetY, eventInfoCopy)); - _updateOffset(offset, rotateInfo.anchor, $ax('#' + elementId).offsetBoundingRect()); - //_updateOffset(offset, rotateInfo.anchor, $axure.fn.getWidgetBoundingRect(elementId)); - rotateHandlesMove = Boolean(rotateInfo && (offset.x || offset.y || rotateInfo.anchor != 'center')); - $ax.event.raiseSyntheticEvent(elementId, 'onRotate'); - } - - var css = null; - var rootLayer = null; - if(deltaHeight != 0 || deltaWidth != 0) { - rootLayer = $ax.move.getRootLayer(elementId); - if(rootLayer) $ax.visibility.pushContainer(rootLayer, false); - css = _getCssForResizingWidget(elementId, eventInfoCopy, resizeInfo.anchor, newWidth, newHeight, oldWidth, oldHeight, delta, options.stop, !rotateHandlesMove); - idToResizeMoveState[elementId].resizeResult = undefined; - } - - if(rotateInfo) { - var rotateDegree = parseFloat($ax.expr.evaluateExpr(rotateInfo.degree, eventInfoCopy)); - - if(rotateHandlesMove) { - var resizeOffset = _applyAnchorToResizeOffset(deltaWidth, deltaHeight, rotateInfo.anchor); - _rotateSingleOffset(elementId, rotateDegree, rotateInfo.rotateType == 'location', delta, offset, options, options.rotateStop, resizeOffset); - } else { - // Not handling move so pass in nop delta - _rotateSingle(elementId, rotateDegree, rotateInfo.rotateType == 'location', { x: 0, y: 0 }, options, options.rotateStop); - if (moves) _fireAnimationFromQueue(elementId, queueTypes.move); - } - } else if(!css && moves) _moveSingleWidget(elementId, delta, options); - - // Have to do it down here to make sure move info is registered - if(moveInfo) $ax.event.raiseSyntheticEvent(elementId, 'onMove'); - - //$ax.event.raiseSyntheticEvent(elementId, 'onResize'); - if (css) { - $ax('#' + elementId).resize(css, resizeInfo, true, moves, function () { - if(rootLayer) $ax.visibility.popContainer(rootLayer, false); - }); - } else { - _fireAnimationFromQueue(elementId, queueTypes.resize); - - $ax.event.raiseSyntheticEvent(elementId, 'onResize'); - } - } - }); - // Nop move (move handled by resize) - if(rotateInfo) animations.push({ id: elementId, type: queueTypes.rotate, func: function () { } }); - if(moves) animations.push({ id: elementId, type: queueTypes.move, func: function () { } }); - } - - _addAnimations(animations); - }; - - var _applyAnchorToResizeOffset = function (deltaWidth, deltaHeight, anchor) { - var offset = {}; - if (anchor.indexOf('left') != -1) offset.x = -deltaWidth / 2; - else if (anchor.indexOf('right') != -1) offset.x = deltaWidth / 2; - if (anchor.indexOf('top') != -1) offset.y = -deltaHeight / 2; - else if (anchor.indexOf('bottom') != -1) offset.y = deltaHeight / 2; - - return offset; - } - - //var _getOldAndNewSize = function (resizeInfo, eventInfo, targetElement) { - // var axObject = $obj(targetElement); - // var oldWidth, oldHeight; - // //textarea can be resized manully by the user, use the textarea child to get the current size - // //because this new size may not be reflected on its parents yet - // if ($ax.public.fn.IsTextArea(axObject.type)) { - // var jObject = $jobj(elementId); - // var textObj = $ax('#' + jObject.children('textarea').attr('id')); - // //maybe we shouldn't use ax obj to get width and height here anymore... - // oldWidth = textObj.width(); - // oldHeight = textObj.height(); - // } else { - // oldWidth = $ax('#' + elementId).width(); - // oldHeight = $ax('#' + elementId).height(); - // } - - // var size = _getSizeFromInfo(resizeInfo, eventInfo, oldHeight, oldWidth, elementId); - // return { oldWidth: oldWidth, oldHeight: oldHeight, newWidth: size.width, newHeight: size.height, change: oldWidth != size.width || oldHeight != size.height }; - //} - - var _getSizeFromInfo = function(resizeInfo, eventInfo, oldWidth, oldHeight, targetElement) { - var oldTarget = eventInfo.targetElement; - eventInfo.targetElement = targetElement; - - var state = _getIdToResizeMoveState(eventInfo)[targetElement]; - if(state && state.resizeResult) return state.resizeResult; - - var width = $ax.expr.evaluateExpr(resizeInfo.width, eventInfo); - var height = $ax.expr.evaluateExpr(resizeInfo.height, eventInfo); - eventInfo.targetElement = oldTarget; - - - // If either one is not a number, use the old value - width = width != "" ? Number(width) : oldWidth; - height = height != "" ? Number(height) : oldHeight; - - width = isNaN(width) ? oldWidth : width; - height = isNaN(height) ? oldHeight : height; - - // can't be negative - var result = { width: Math.max(width, 0), height: Math.max(height, 0) }; - if(state) state.resizeResult = result; - return result; - } - - //var _queueResize = function (elementId, css, resizeInfo) { - // var resizeFunc = function() { - // $ax('#' + elementId).resize(css, resizeInfo, true); - // //$ax.public.fn.resize(elementId, css, resizeInfo, true); - // }; - // var obj = $obj(elementId); - // var moves = resizeInfo.anchor != "top left" || ($ax.public.fn.IsDynamicPanel(obj.type) && ((obj.fixedHorizontal && obj.fixedHorizontal == 'center') || (obj.fixedVertical && obj.fixedVertical == 'middle'))) - // if(!moves) { - // _addAnimation(elementId, queueTypes.resize, resizeFunc); - // } else { - // var animations = []; - // animations[0] = { id: elementId, type: queueTypes.resize, func: resizeFunc }; - // animations[1] = { id: elementId, type: queueTypes.move, func: function() {}}; // Nop func - resize handles move and firing from queue - // _addAnimations(animations); - // } - //}; - - //should clean this function and - var _getCssForResizingWidget = function (elementId, eventInfo, anchor, newWidth, newHeight, oldWidth, oldHeight, delta, stop, handleMove) { - var ratio = stop.instant ? 1 : (stop.end - stop.start) / (stop.len - stop.start); - var deltaWidth = (newWidth - oldWidth) * ratio; - var deltaHeight = (newHeight - oldHeight) * ratio; - if(stop.instant || stop.end == stop.len) { - var idToResizeMoveState = _getIdToResizeMoveState(eventInfo); - if(idToResizeMoveState[elementId]) idToResizeMoveState[elementId].resizeResult = undefined; - } - - var css = {}; - css.height = oldHeight + deltaHeight; - - var obj = $obj(elementId); - //if it's 100% width, don't change its width - if($ax.dynamicPanelManager.isPercentWidthPanel(obj)) var is100Dp = true; - else css.width = oldWidth + deltaWidth; - - var jobj = $jobj(elementId); - //if this is pinned dp, we will mantain the pin, no matter how you resize it; so no need changes left or top - //NOTE: currently only pinned DP has position == fixed - if(jobj.css('position') == 'fixed') { - if(obj.fixedHorizontal && obj.fixedHorizontal == 'center') css['margin-left'] = '+=' + delta.x; - if(obj.fixedVertical && obj.fixedVertical == 'middle') css['margin-top'] = '+=' + delta.y; - return css; - } - - // If it is pinned, but temporarily not fixed because it is wrappen in a container, then just make sure to anchor it correctly - if(obj.fixedVertical) { - if(obj.fixedVertical == 'middle') anchor = obj.fixedHorizontal; - else anchor = obj.fixedVertical + (obj.fixedHorizontal == 'center' ? '' : ' ' + obj.fixedHorizontal); - - } - - //use position relative to parents - //var position = obj.generateCompound ? $ax.public.fn.getWidgetBoundingRect(elementId) : $ax.public.fn.getPositionRelativeToParent(elementId); - - - var locationShift; - switch(anchor) { - case "top left": - locationShift = { x: 0, y: 0 }; break; - case "top": - locationShift = { x: -deltaWidth / 2.0, y: 0.0 }; break; - case "top right": - locationShift = { x: -deltaWidth, y: 0.0 }; break; - case "left": - locationShift = { x: 0.0, y: -deltaHeight / 2.0 }; break; - case "center": - locationShift = { x: -deltaWidth / 2.0, y: -deltaHeight / 2.0 }; break; - case "right": - locationShift = { x: -deltaWidth, y: -deltaHeight / 2.0 }; break; - case "bottom left": - locationShift = { x: 0.0, y: -deltaHeight }; break; - case "bottom": - locationShift = { x: -deltaWidth/2.0, y: -deltaHeight }; break; - case "bottom right": - locationShift = { x: -deltaWidth, y: -deltaHeight }; break; - } - - if(handleMove) { - if(jobj.css('position') === 'absolute') { - css.left = $ax.getNumFromPx(jobj.css('left')) + locationShift.x + delta.x; - css.top = $ax.getNumFromPx(jobj.css('top')) + locationShift.y + delta.y; - } else { - var axQuery = $ax('#' + elementId); - var offsetLocation = axQuery.offsetLocation(); - css.left = offsetLocation.left + locationShift.x + delta.x; - css.top = offsetLocation.top + locationShift.y + delta.y; - //css.left = axQuery.left(true) + locationShift.x + delta.x; - //css.top = axQuery.top(true) + locationShift.y + delta.y; - } - } else { - delta.x += locationShift.x; - delta.y += locationShift.y; - } - - css.deltaX = locationShift.x + delta.x; - css.deltaY = locationShift.y + delta.y; - - return css; - }; - - - var _getCssForResizingLayerChild = function (elementId, anchor, layerBoundingRect, widthChangedPercent, heightChangedPercent, deltaLoc) { - var boundingRect = $ax('#' + elementId).offsetBoundingRect(); - //var boundingRect = $ax.public.fn.getWidgetBoundingRect(elementId); - var childCenterPoint = boundingRect.centerPoint; - - var currentSize = $ax('#' + elementId).size(); - var newWidth = currentSize.width + currentSize.width * widthChangedPercent; - var newHeight = currentSize.height + currentSize.height * heightChangedPercent; - - var css = {}; - css.height = newHeight; - - var obj = $obj(elementId); - //if it's 100% width, don't change its width and left - var changeLeft = true; - if($ax.dynamicPanelManager.isPercentWidthPanel(obj)) changeLeft = false; - else css.width = newWidth; - - var jobj = $jobj(elementId); - //if this is pinned dp, we will mantain the pin, no matter how you resize it; so no need changes left or top - //NOTE: currently only pinned DP has position == fixed - if(jobj.css('position') == 'fixed') return css; - //use bounding rect position relative to parents to calculate delta - //var axObj = $ax('#' + elementId); - // This will be absolute world coordinates, but we want body coordinates. - var offsetLocation = $ax('#' + elementId).offsetLocation(); - var currentLeft = offsetLocation.left; - var currentTop = offsetLocation.top; - //var currentLeft = axObj.locRelativeIgnoreLayer(false); - //var currentTop = axObj.locRelativeIgnoreLayer(true); - - var resizable = $ax.public.fn.IsResizable(obj.type); - if(anchor.indexOf("top") > -1) { - var topDelta = (currentTop - layerBoundingRect.top) * heightChangedPercent; - if(!resizable && Math.round(topDelta)) topDelta += currentSize.height * heightChangedPercent; - } else if(anchor.indexOf("bottom") > -1) { - if(resizable) topDelta = (currentTop - layerBoundingRect.bottom) * heightChangedPercent; - else { - var bottomDelta = Math.round(currentTop + currentSize.height - layerBoundingRect.bottom) * heightChangedPercent; - if(bottomDelta) topDelta = bottomDelta - currentSize.height * heightChangedPercent; - else topDelta = 0; - } - } else { //center vertical - if(resizable) topDelta = (childCenterPoint.y - layerBoundingRect.centerPoint.y)*heightChangedPercent - currentSize.height*heightChangedPercent/2; - else { - var centerTopChange = Math.round(childCenterPoint.y - layerBoundingRect.centerPoint.y)*heightChangedPercent; - if(centerTopChange > 0) topDelta = centerTopChange + Math.abs(currentSize.height * heightChangedPercent / 2); - else if(centerTopChange < 0) topDelta = centerTopChange - Math.abs(currentSize.height * heightChangedPercent / 2); - else topDelta = 0; - } - } - - if(changeLeft) { - if(anchor.indexOf("left") > -1) { - var leftDelta = (currentLeft - layerBoundingRect.left) * widthChangedPercent; - if(!resizable && Math.round(leftDelta)) leftDelta += currentSize.width * widthChangedPercent; - } else if(anchor.indexOf("right") > -1) { - if(resizable) leftDelta = (currentLeft - layerBoundingRect.right) * widthChangedPercent; - else { - var rightDelta = Math.round(currentLeft + currentSize.width - layerBoundingRect.right) * widthChangedPercent; - if(rightDelta) leftDelta = rightDelta - currentSize.width * widthChangedPercent; - else leftDelta = 0; - } - } else { //center horizontal - if(resizable) leftDelta = (childCenterPoint.x - layerBoundingRect.centerPoint.x)*widthChangedPercent - currentSize.width*widthChangedPercent/2; - else { - var centerLeftChange = Math.round(childCenterPoint.x - layerBoundingRect.centerPoint.x) * widthChangedPercent; - if(centerLeftChange > 0) leftDelta = centerLeftChange + Math.abs(currentSize.width * widthChangedPercent / 2); - else if(centerLeftChange < 0) leftDelta = centerLeftChange - Math.abs(currentSize.width * widthChangedPercent / 2); - else leftDelta = 0; - } - } - } - - if(topDelta) deltaLoc.y += topDelta; - if(leftDelta && changeLeft) deltaLoc.x += leftDelta; - - return css; - }; - - _actionHandlers.setPanelOrder = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.panelPaths.length; i++) { - var func = action.panelPaths[i].setOrderInfo.bringToFront ? 'bringToFront' : 'sendToBack'; - var elementIds = $ax.getElementIdsFromPath(action.panelPaths[i].panelPath, eventInfo); - for(var j = 0; j < elementIds.length; j++) $ax('#' + elementIds[j])[func](); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.modifyDataSetEditItems = function(eventInfo, actions, index) { - var action = actions[index]; - var add = action.repeatersToAddTo; - var repeaters = add || action.repeatersToRemoveFrom; - var itemId; - for(var i = 0; i < repeaters.length; i++) { - var data = repeaters[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(data.path, eventInfo)[0]; - if(!id) continue; - - if(data.addType == 'this') { - var scriptId = $ax.repeater.getScriptIdFromElementId(eventInfo.srcElement); - itemId = $ax.repeater.getItemIdFromElementId(eventInfo.srcElement); - var repeaterId = $ax.getParentRepeaterFromScriptId(scriptId); - if(add) $ax.repeater.addEditItems(repeaterId, [itemId]); - else $ax.repeater.removeEditItems(repeaterId, [itemId]); - } else if(data.addType == 'all') { - var allItems = $ax.repeater.getAllItemIds(id); - if(add) $ax.repeater.addEditItems(id, allItems); - else $ax.repeater.removeEditItems(id, allItems); - } else { - var oldTarget = eventInfo.targetElement; - var itemIds = $ax.repeater.getAllItemIds(id); - var itemIdsToAdd = []; - for(var j = 0; j < itemIds.length; j++) { - itemId = itemIds[j]; - eventInfo.targetElement = $ax.repeater.createElementId(id, itemId); - if($ax.expr.evaluateExpr(data.query, eventInfo) == "true") { - itemIdsToAdd[itemIdsToAdd.length] = String(itemId); - } - eventInfo.targetElement = oldTarget; - } - if(add) $ax.repeater.addEditItems(id, itemIdsToAdd); - else $ax.repeater.removeEditItems(id, itemIdsToAdd); - } - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _action.repeaterInfoNames = { addItemsToDataSet: 'dataSetsToAddTo', deleteItemsFromDataSet: 'dataSetItemsToRemove', updateItemsInDataSet: 'dataSetsToUpdate', - addFilterToRepeater: 'repeatersToAddFilter', removeFilterFromRepeater: 'repeatersToRemoveFilter', - addSortToRepeater: 'repeaterToAddSort', removeSortFromRepeater: 'repeaterToRemoveSort', - setRepeaterToPage: 'repeatersToSetPage', setItemsPerRepeaterPage: 'repeatersToSetItemCount' - }; - - _actionHandlers.addItemsToDataSet = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.dataSetsToAddTo.length; i++) { - var datasetInfo = action.dataSetsToAddTo[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(datasetInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - var dataset = datasetInfo.data; - - for(var j = 0; j < dataset.length; j++) $ax.repeater.addItem(id, $ax.deepCopy(dataset[j]), eventInfo); - if(dataset.length) _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.deleteItemsFromDataSet = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.dataSetItemsToRemove.length; i++) { - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var deleteInfo = action.dataSetItemsToRemove[i]; - var id = $ax.getElementIdsFromPath(deleteInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - $ax.repeater.deleteItems(id, eventInfo, deleteInfo.type, deleteInfo.rule); - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.updateItemsInDataSet = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.dataSetsToUpdate.length; i++) { - var dataSet = action.dataSetsToUpdate[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(dataSet.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - $ax.repeater.updateEditItems(id, dataSet.props, eventInfo, dataSet.type, dataSet.rule); - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.setRepeaterToDataSet = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToSet.length; i++) { - var setRepeaterInfo = action.repeatersToSet[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(setRepeaterInfo.path, eventInfo)[0]; - if(!id) continue; - $ax.repeater.setDataSet(id, setRepeaterInfo.localDataSetId); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.addFilterToRepeater = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToAddFilter.length; i++) { - var addFilterInfo = action.repeatersToAddFilter[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(addFilterInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - $ax.repeater.addFilter(id, addFilterInfo.removeOtherFilters, addFilterInfo.label, addFilterInfo.filter, eventInfo.srcElement); - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.removeFilterFromRepeater = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToRemoveFilter.length; i++) { - var removeFilterInfo = action.repeatersToRemoveFilter[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(removeFilterInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - if(removeFilterInfo.removeAll) $ax.repeater.removeFilter(id); - else if(removeFilterInfo.filterName != '') { - $ax.repeater.removeFilter(id, removeFilterInfo.filterName); - } - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.addSortToRepeater = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToAddSort.length; i++) { - var addSortInfo = action.repeatersToAddSort[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(addSortInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - $ax.repeater.addSort(id, addSortInfo.label, addSortInfo.columnName, addSortInfo.ascending, addSortInfo.toggle, addSortInfo.sortType); - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.removeSortFromRepeater = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToRemoveSort.length; i++) { - var removeSortInfo = action.repeatersToRemoveSort[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(removeSortInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - if(removeSortInfo.removeAll) $ax.repeater.removeSort(id); - else if(removeSortInfo.sortName != '') $ax.repeater.removeSort(id, removeSortInfo.sortName); - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.setRepeaterToPage = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToSetPage.length; i++) { - var setPageInfo = action.repeatersToSetPage[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(setPageInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - var oldTarget = eventInfo.targetElement; - eventInfo.targetElement = id; - $ax.repeater.setRepeaterToPage(id, setPageInfo.pageType, setPageInfo.pageValue, eventInfo); - eventInfo.targetElement = oldTarget; - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.setItemsPerRepeaterPage = function(eventInfo, actions, index) { - var action = actions[index]; - - for(var i = 0; i < action.repeatersToSetItemCount.length; i++) { - var setItemCountInfo = action.repeatersToSetItemCount[i]; - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(setItemCountInfo.path, eventInfo)[0]; - if(!id || _ignoreAction(id)) continue; - - if(setItemCountInfo.noLimit) $ax.repeater.setNoItemLimit(id); - else $ax.repeater.setItemLimit(id, setItemCountInfo.itemCountValue, eventInfo); - _addRefresh(id); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.refreshRepeater = function(eventInfo, actions, index) { - // We use this as a psudo action now. - var action = actions[index]; - for (var i = 0; i < action.repeatersToRefresh.length; i++) { - // Grab the first one because repeaters must have only element id, as they cannot be inside repeaters - // or none if unplaced - var id = $ax.getElementIdsFromPath(action.repeatersToRefresh[i], eventInfo)[0]; - if(id) _tryRefreshRepeater(id, eventInfo); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - var _tryRefreshRepeater = function(id, eventInfo) { - var idIndex = _repeatersToRefresh.indexOf(id); - if(idIndex == -1) return; - - $ax.splice(_repeatersToRefresh, idIndex, 1); - $ax.repeater.refreshRepeater(id, eventInfo); - }; - - _action.tryRefreshRepeaters = function(ids, eventInfo) { - for(var i = 0; i < ids.length; i++) _tryRefreshRepeater(ids[i], eventInfo); - }; - - _actionHandlers.scrollToWidget = function(eventInfo, actions, index) { - var action = actions[index]; - var elementIds = $ax.getElementIdsFromPath(action.objectPath, eventInfo); - if(elementIds.length > 0) $ax('#' + elementIds[0]).scroll(action.options); - - _dispatchAction(eventInfo, actions, index + 1); - }; - - - _actionHandlers.enableDisableWidgets = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.pathToInfo.length; i++) { - var elementIds = $ax.getElementIdsFromPath(action.pathToInfo[i].objectPath, eventInfo); - var enable = action.pathToInfo[i].enableDisableInfo.enable; - for(var j = 0; j < elementIds.length; j++) $ax('#' + elementIds[j]).enabled(enable); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.setImage = function(eventInfo, actions, index) { - var oldTarget = eventInfo.targetElement; - var action = actions[index]; - var view = $ax.adaptive.currentViewId; - - eventInfo.image = true; - for(var i = 0; i < action.imagesToSet.length; i++) { - var imgInfo = action.imagesToSet[i]; - if (view && imgInfo.adaptive[view]) imgInfo = imgInfo.adaptive[view]; - else imgInfo = imgInfo.base; - var elementIds = $ax.getElementIdsFromPath(action.imagesToSet[i].objectPath, eventInfo); - - for(var j = 0; j < elementIds.length; j++) { - var elementId = elementIds[j]; - - eventInfo.targetElement = elementId; - var evaluatedImgs = _evaluateImages(imgInfo, eventInfo); - - var img = evaluatedImgs.normal; - if($ax.style.IsWidgetDisabled(elementId)) { - if(imgInfo.disabled) img = evaluatedImgs.disabled; - } else if($ax.style.IsWidgetSelected(elementId)) { - if(imgInfo.selected) img = evaluatedImgs.selected; - } else if($ax.event.mouseDownObjectId == elementId && imgInfo.mouseDown) img = evaluatedImgs.mouseDown; - else if($ax.event.mouseOverIds.indexOf(elementId) != -1 && imgInfo.mouseOver) { - img = evaluatedImgs.mouseOver; - //Update mouseOverObjectId - var currIndex = $ax.event.mouseOverIds.indexOf($ax.event.mouseOverObjectId); - var imgIndex = $ax.event.mouseOverIds.indexOf(elementId); - if(currIndex < imgIndex) $ax.event.mouseOverObjectId = elementId; - } else if(imgInfo.mouseOver && elementId == eventInfo.srcElement) { - img = evaluatedImgs.mouseOver; - } - - // $('#' + $ax.repeater.applySuffixToElementId(elementId, '_img')).attr('src', img); - $jobj($ax.GetImageIdFromShape(elementId)).attr('src', img); - - //Set up overrides - $ax.style.mapElementIdToImageOverrides(elementId, evaluatedImgs); - $ax.style.updateElementIdImageStyle(elementId); - - if(evaluatedImgs.mouseOver || evaluatedImgs.mouseDown) $ax.event.updateIxStyleEvents(elementId); - } - } - eventInfo.targetElement = oldTarget; - eventInfo.image = false; - - _dispatchAction(eventInfo, actions, index + 1); - }; - - var _evaluateImages = function(imgInfo, eventInfo) { - var retVal = {}; - for(var state in imgInfo) { - if(!imgInfo.hasOwnProperty(state)) continue; - var img = imgInfo[state][$ax.adaptive.getSketchKey()] || $ax.expr.evaluateExpr(imgInfo[state].literal, eventInfo); - if(!img) img = $axure.utils.getTransparentGifPath(); - retVal[state] = img; - } - return retVal; - }; - - $ax.clearRepeaterImageOverrides = function(repeaterId) { - var childIds = $ax.getChildElementIdsForRepeater(repeaterId); - for(var i = childIds; i < childIds.length; i++) $ax.style.deleteElementIdToImageOverride(childIds[i]); - }; - - _actionHandlers.setFocusOnWidget = function(eventInfo, actions, index) { - var action = actions[index]; - if(action.objectPaths.length > 0) { - var elementIds = $ax.getElementIdsFromPath(action.objectPaths[0], eventInfo); - if(elementIds.length > 0) { - $ax('#' + elementIds[0]).focus(); - //if select text and not in placeholder mode, then select all text - if(action.selectText && !$ax.placeholderManager.isActive(elementIds[0])) { - var elementChildren = document.getElementById(elementIds[0]).children; - //find the input or textarea element - for(var i = 0; i < elementChildren.length; i++) { - if (elementChildren[i].id.indexOf('_input') == -1) continue; - var elementTagName = elementChildren[i].tagName; - if(elementTagName && (elementTagName.toLowerCase() == "input" || elementTagName.toLowerCase() == "textarea")) { - elementChildren[i].select(); - } - } - } - } - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.expandCollapseTree = function(eventInfo, actions, index) { - var action = actions[index]; - for(var i = 0; i < action.pathToInfo.length; i++) { - var pair = action.pathToInfo[i]; - var elementIds = $ax.getElementIdsFromPath(pair.treeNodePath, eventInfo); - for(var j = 0; j < elementIds.length; j++) $ax('#' + elementIds[j]).expanded(pair.expandCollapseInfo.expand); - } - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.other = function(eventInfo, actions, index) { - var action = actions[index]; - $ax.navigate({ - url: $axure.utils.getOtherPath() + "#other=" + encodeURI(action.otherDescription), - target: "popup", - includeVariables: false, - popupOptions: action.popup - }); - - _dispatchAction(eventInfo, actions, index + 1); - }; - - _actionHandlers.fireEvents = function(eventInfo, actions, index) { - var action = actions[index]; - //look for the nearest element id - - var objId = eventInfo.srcElement; - var thisWidget = eventInfo.thiswidget; - var obj = $ax.getObjectFromElementId(objId); - var rdoId = obj ? $ax.getRdoParentFromElementId(objId) : ""; - var rdo = $ax.getObjectFromElementId(rdoId); - var page = rdo ? $ax.pageData.masters[rdo.masterId] : $ax.pageData.page; - - // Check if rdo should be this - var oldIsMasterEvent = eventInfo.isMasterEvent; - if (obj && $ax.public.fn.IsReferenceDiagramObject(obj.type) && eventInfo.isMasterEvent) { - rdoId = objId; - rdo = obj; - page = $ax.pageData.masters[rdo.masterId]; - } - - for(var i = 0; i < action.firedEvents.length; i++) { - var firedEvent = action.firedEvents[i]; - var isPage = firedEvent.objectPath.length == 0; - var targetObjIds = isPage ? [rdoId] : $ax.getElementIdsFromPath(firedEvent.objectPath, eventInfo); - for (var j = 0; j < targetObjIds.length; j++) { - var targetObjId = targetObjIds[j]; - var targetObj = isPage ? rdo : $ax.getObjectFromElementId(targetObjId); - - eventInfo.srcElement = targetObjId || ''; - eventInfo.thiswidget = $ax.getWidgetInfo(eventInfo.srcElement); - - eventInfo.isMasterEvent = false; - var raisedEvents = firedEvent.raisedEventIds; - if(raisedEvents) { - for(var k = 0; k < raisedEvents.length; k++) { - var event = targetObj.interactionMap && targetObj.interactionMap.raised && targetObj.interactionMap.raised[raisedEvents[k]]; - if(event) $ax.event.handleEvent(targetObjId, eventInfo, event, false, true); - } - } - - if(isPage) { - eventInfo.isMasterEvent = true; - eventInfo.label = $ax.pageData.page.name; - eventInfo.friendlyType = 'Page'; - } - - var firedTarget = isPage ? page : targetObj; - var firedEventNames = firedEvent.firedEventNames; - if(firedEventNames) { - for(k = 0; k < firedEventNames.length; k++) { - event = firedTarget.interactionMap && firedTarget.interactionMap[firedEventNames[k]]; - if(event) $ax.event.handleEvent(isPage ? '' : targetObjId, eventInfo, event, false, true); - } - } - if(isPage) eventInfo.isMasterEvent = oldIsMasterEvent; - } - eventInfo.srcElement = objId; - eventInfo.thiswidget = thisWidget; - - eventInfo.isMasterEvent = oldIsMasterEvent; - } - - _dispatchAction(eventInfo, actions, index + 1); - }; -}); diff --git a/web/main/static/resources/scripts/axure/adaptive.js b/web/main/static/resources/scripts/axure/adaptive.js deleted file mode 100644 index 37a362e..0000000 --- a/web/main/static/resources/scripts/axure/adaptive.js +++ /dev/null @@ -1,771 +0,0 @@ -$axure.internal(function($ax) { - $ax.adaptive = {}; - - $axure.utils.makeBindable($ax.adaptive, ["viewChanged"]); - - var _auto = true; - var _autoIsHandledBySidebar = false; - - var _views; - var _idToView; - var _enabledViews = []; - - var _initialViewToLoad; - var _initialViewSizeToLoad; - - var _loadFinished = false; - $ax.adaptive.loadFinished = function() { - if(_loadFinished) return; - _loadFinished = true; - if($ax.adaptive.currentViewId) $ax.viewChangePageAndMasters(); - else $ax.postAdaptiveViewChanged(); - }; - - var _handleResize = function(forceSwitchTo) { - if(!_auto) return; - if(_auto && _autoIsHandledBySidebar && !forceSwitchTo) return; - - var $window = $(window); - var height = $window.height(); - var width = $window.width(); - - var toView = _getAdaptiveView(width, height); - var toViewId = toView && toView.id; - - _switchView(toViewId, forceSwitchTo); - }; - - var _setAuto = $ax.adaptive.setAuto = function(val) { - if(_auto != val) { - _auto = Boolean(val); - } - }; - - var _setLineImage = function(id, imageUrl) { - $jobj(id).attr('src', imageUrl); - }; - - var _switchView = function (viewId, forceSwitchTo) { - //if(!$ax.pageData.isAdaptiveEnabled) return; - - var previousViewId = $ax.adaptive.currentViewId; - if(typeof previousViewId == 'undefined') previousViewId = ''; - if(typeof viewId == 'undefined') viewId = ''; - if (viewId == previousViewId) { - if(forceSwitchTo) $ax.postAdaptiveViewChanged(forceSwitchTo); - return; - } - - $ax('*').each(function(obj, elementId) { - if (!$ax.public.fn.IsTreeNodeObject(obj.type)) return; - if(!obj.hasOwnProperty('isExpanded')) return; - - var query = $ax('#' + elementId); - var defaultExpanded = obj.isExpanded; - - query.expanded(defaultExpanded); - }); - - // reset all the inline positioning from move and rotate actions including size and transformation - $axure('*').each(function (diagramObject, elementId) { - if(diagramObject.isContained) return; - if($ax.getParentRepeaterFromElementIdExcludeSelf(elementId)) return; - - var element = document.getElementById(elementId); - if(element) { - var resetCss = { - top: "", left: "", width: "", height: "", opacity: "", - transform: "", webkitTransform: "", MozTransform: "", msTransform: "", OTransform: "" - }; - var query = $(element); - query.css(resetCss); - var isPanel = $ax.public.fn.IsDynamicPanel(diagramObject.type); - if(!isPanel || diagramObject.fitToContent) { //keeps size on the panel states when switching adaptive views to optimize fit to panel - if(diagramObject.fitToContent) $ax.dynamicPanelManager.setFitToContentCss(elementId, true); - var children = query.children(); - if(children.length) children.css(resetCss); - } - - $ax.dynamicPanelManager.resetFixedPanel(diagramObject, element); - $ax.dynamicPanelManager.resetAdaptivePercentPanel(diagramObject, element); - } - }); - - $ax.adaptive.currentViewId = viewId; // we need to set this so the enabled and selected styles will apply properly - if(previousViewId) { - $ax.style.clearAdaptiveStyles(); - $('*').removeClass(previousViewId); - } else { - $ax.style.reselectElements(); - } - - $axure('*').each(function (obj, elementId) { - if($ax.getParentRepeaterFromElementIdExcludeSelf(elementId)) return; - - $ax.style.updateElementIdImageStyle(elementId); // When image override exists, fix styling/borders - }); - - //$ax.style.startSuspendTextAlignment(); - - // reset all the images only if we're going back to the default view - if(!viewId) { - $axure('*').each(function (diagramObject, elementId) { - if($ax.getParentRepeaterFromElementIdExcludeSelf(elementId)) return; - - $ax.placeholderManager.refreshPlaceholder(elementId); - - var images = diagramObject.images; - if(diagramObject.type == 'horizontalLine' || diagramObject.type == 'verticalLine') { - var startImg = images['start~']; - _setLineImage(elementId + "_start", startImg); - var endImg = images['end~']; - _setLineImage(elementId + "_end", endImg); - var lineImg = images['line~']; - _setLineImage(elementId + "_line", lineImg); - } else if(diagramObject.type == $ax.constants.CONNECTOR_TYPE) { - _setAdaptiveConnectorImages(elementId, images, ''); - } else if(images) { - if (diagramObject.generateCompound) { - - if($ax.style.IsWidgetDisabled(elementId)) { - disabledImage = _getImageWithTag(images, 'disabled~'); - if(disabledImage) $ax.style.applyImage(elementId, disabledImage, 'disabled'); - return; - } - if($ax.style.IsWidgetSelected(elementId)) { - selectedImage = _getImageWithTag(images, 'selected~'); - if(selectedImage) $ax.style.applyImage(elementId, selectedImage, 'selected'); - return; - } - $ax.style.applyImage(elementId, _getImageWithTag(images, 'normal~'), 'normal'); - } else { - if ($ax.style.IsWidgetDisabled(elementId)) { - var disabledImage = _matchImage(elementId, images, [], 'disabled', true); - if (disabledImage) $ax.style.applyImage(elementId, disabledImage, 'disabled'); - return; - } - if ($ax.style.IsWidgetSelected(elementId)) { - var selectedImage = _matchImage(elementId, images, [], 'selected', true); - if (selectedImage) $ax.style.applyImage(elementId, selectedImage, 'selected'); - return; - } - var normalImage = _matchImage(elementId, images, [], 'normal', true); - $ax.style.applyImage(elementId, normalImage, 'normal'); - } - } - - //align all text - var child = $jobj(elementId).children('.text'); - if(child.length) $ax.style.transformTextWithVerticalAlignment(child[0].id, function() { }); - }); - // we have to reset visibility if we aren't applying a new view - $ax.visibility.resetLimboAndHiddenToDefaults(); - $ax.visibility.clearMovedAndResized(); - $ax.repeater.refreshAllRepeaters(); - $ax.dynamicPanelManager.updateParentsOfNonDefaultFitPanels(); - $ax.dynamicPanelManager.updatePercentPanelCache($ax('*')); - } else { - $ax.visibility.clearLimboAndHidden(); - $ax.visibility.clearMovedAndResized(); - _applyView(viewId); - $ax.repeater.refreshAllRepeaters(); - $ax.dynamicPanelManager.updateAllLayerSizeCaches(); - $ax.dynamicPanelManager.updateParentsOfNonDefaultFitPanels(); - } - - $ax.annotation.updateAllFootnotes(); - //$ax.style.resumeSuspendTextAlignment(); - - $ax.adaptive.triggerEvent('viewChanged', {}); - if(_loadFinished) $ax.viewChangePageAndMasters(forceSwitchTo); - }; - - var _getImageWithTag = function(image, tag) { - var flattened = {}; - for (var component in image) { - var componentImage = image[component][tag]; - if(componentImage) flattened[component] = componentImage; - } - return flattened; - } - - // gets the inheritance chain of a particular view. - var _getAdaptiveIdChain = $ax.adaptive.getAdaptiveIdChain = function(viewId) { - if(!viewId) return []; - var view = _idToView[viewId]; - var chain = []; - var current = view; - while(current) { - chain[chain.length] = current.id; - current = _idToView[current.baseViewId]; - } - return chain.reverse(); - }; - - var _getMasterAdaptiveIdChain = $ax.adaptive.getMasterAdaptiveIdChain = function (masterId, viewId) { - if (!viewId) return []; - - var master = $ax.pageData.masters[masterId]; - var masterViews = master.adaptiveViews; - var idToMasterView = {}; - if (masterViews && masterViews.length > 0) { - for (var i = 0; i < masterViews.length; i++) { - var view = masterViews[i]; - idToMasterView[view.id] = view; - } - } - - if (!idToMasterView) return []; - - var view = idToMasterView[viewId]; - var chain = []; - var current = view; - while (current) { - chain[chain.length] = current.id; - current = idToMasterView[current.baseViewId]; - } - return chain.reverse(); - }; - - var _getPageStyle = $ax.adaptive.getPageStyle = function() { - var currentViewId = $ax.adaptive.currentViewId; - var adaptiveChain = _getAdaptiveIdChain(currentViewId); - - var currentStyle = $.extend({}, $ax.pageData.page.style); - for(var i = 0; i < adaptiveChain.length; i++) { - var viewId = adaptiveChain[i]; - $.extend(currentStyle, $ax.pageData.page.adaptiveStyles[viewId]); - } - - return currentStyle; - }; - - var _setAdaptiveLineImages = function(elementId, images, viewIdChain) { - for(var i = viewIdChain.length - 1; i >= 0; i--) { - var viewId = viewIdChain[i]; - var startImg = images['start~' + viewId]; - if(startImg) { - _setLineImage(elementId + "_start", startImg); - var endImg = images['end~' + viewId]; - _setLineImage(elementId + "_end", endImg); - var lineImg = images['line~' + viewId]; - _setLineImage(elementId + "_line", lineImg); - break; - } - } - }; - - var _setAdaptiveConnectorImages = function (elementId, images, view) { - var conn = $jobj(elementId); - var count = conn.children().length-1; // -1 for rich text panel - for(var i = 0; i < count; i++) { - var img = images['' + i + '~' + view]; - $jobj(elementId + '_seg' + i).attr('src', img); - } - }; - - var _applyView = $ax.adaptive.applyView = function(viewId, query) { - var limboIds = {}; - var hiddenIds = {}; - - var jquery; - if(query) { - jquery = query.jQuery(); - jquery = jquery.add(jquery.find('*')); - var jqueryAnn = $ax.annotation.jQueryAnn(query); - jquery = jquery.add(jqueryAnn); - } else { - jquery = $('*').not('#ios-safari-fixed'); - query = $ax('*'); - } - jquery.addClass(viewId); - var viewIdChain = _getAdaptiveIdChain(viewId); - // this could be made more efficient by computing it only once per object - query.each(function(diagramObject, elementId) { - _applyAdaptiveViewOnObject(diagramObject, elementId, viewIdChain, viewId, limboIds, hiddenIds); - }); - - $ax.visibility.addLimboAndHiddenIds(limboIds, hiddenIds, query); - //$ax.dynamicPanelManager.updateAllFitPanelsAndLayerSizeCaches(); - $ax.dynamicPanelManager.updatePercentPanelCache(query); - }; - - var _applyAdaptiveViewOnObject = function(diagramObject, elementId, viewIdChain, viewId, limboIds, hiddenIds) { - var adaptiveChain = []; - for(var i = 0; i < viewIdChain.length; i++) { - var viewId = viewIdChain[i]; - var viewStyle = diagramObject.adaptiveStyles[viewId]; - if(viewStyle) { - adaptiveChain[adaptiveChain.length] = viewStyle; - if (viewStyle.size) $ax.public.fn.convertToSingleImage($jobj(elementId)); - } - } - - var state = $ax.style.generateState(elementId); - - // set the image - var images = diagramObject.images; - if(images) { - if(diagramObject.type == 'horizontalLine' || diagramObject.type == 'verticalLine') { - _setAdaptiveLineImages(elementId, images, viewIdChain); - } else if (diagramObject.type == $ax.constants.CONNECTOR_TYPE) { - _setAdaptiveConnectorImages(elementId, images, viewId); - } else if (diagramObject.generateCompound) { - var compoundUrl = _matchImageCompound(diagramObject, elementId, viewIdChain, state); - if (compoundUrl) $ax.style.applyImage(elementId, compoundUrl, state); - }else { - var imgUrl = _matchImage(elementId, images, viewIdChain, state); - if(imgUrl) $ax.style.applyImage(elementId, imgUrl, state); - } - } - // addaptive override style (not including default style props) - var adaptiveStyle = $ax.style.computeAllOverrides(elementId, undefined, state, viewId); - - // this style INCLUDES the object's my style - var compoundStyle = $.extend({}, diagramObject.style, adaptiveStyle); - - // if (diagramObject.owner.type == 'Axure:Master' && diagramObject.adaptiveStyles) { - // adaptiveStyle = $ax.style.computeFullStyle(elementId, state, viewId); - // } - - if(!diagramObject.isContained) { - $ax.style.setAdaptiveStyle(elementId, adaptiveStyle); - } - - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - if(compoundStyle.limbo && !diagramObject.isContained) limboIds[scriptId] = true; - // sigh, javascript. we need the === here because undefined means not overriden - if(compoundStyle.visible === false) hiddenIds[scriptId] = true; - }; - - var _matchImage = function(id, images, viewIdChain, state, doNotProgress) { - var override = $ax.style.getElementImageOverride(id, state); - if(override) return override; - - if(!images) return undefined; - - let scriptId = $ax.repeater.getScriptIdFromElementId(id); - - if(state == 'disabled' && $ax.style.IsWidgetSelected(id) || state == 'selected' && $ax.style.IsWidgetDisabled(id)) { - let diagramObject = $ax.getObjectFromElementId(id); - if(diagramObject && $ax.public.fn.IsSelectionButton(diagramObject.type)) { - var selectedDisabled = $ax.constants.SELECTED_DISABLED; - } - } - - // first check all the images for this state - for(let i = viewIdChain.length - 1; i >= 0; i--) { - let viewId = viewIdChain[i]; - if(selectedDisabled) { - let img = findImage(images, scriptId, selectedDisabled, viewId) - if(img) return img; - } else { - let img = findImage(images, scriptId, state, viewId); - if (img) return img; - } - } - // check for the default state style - if(selectedDisabled) { - let defaultStateImage = findImage(images, scriptId, selectedDisabled) - if(defaultStateImage) return defaultStateImage; - } else { - let defaultStateImage = findImage(images, scriptId, state); - if (defaultStateImage) return defaultStateImage; - } - - if(doNotProgress) return undefined; - - state = $ax.style.progessState(state); - if (state) return _matchImage(scriptId, images, viewIdChain, state); - - // SHOULD NOT REACH HERE! NORMAL SHOULD ALWAYS CATCH AT THE DEFAULT! - return images['normal~']; // this is the default - }; - - let findImage = function(images, scriptId, state, viewId) { - if(!images) return undefined; - - if(!viewId) viewId = ""; - let withScript = scriptId + "~" + state + "~" + viewId; - let img = images[withScript]; - if(!img) img = images[state + "~" + viewId]; - return img; - } - - var _matchImageCompound = function(diagramObject, id, viewIdChain, state) { - var images = []; - for(var i = 0; i < diagramObject.compoundChildren.length; i++) { - var component = diagramObject.compoundChildren[i]; - images[component] = _matchImage(id, diagramObject.images[component], viewIdChain, state); - } - return images; - }; - - - - $ax.adaptive.getImageForStateAndView = function(id, state) { - var viewIdChain = _getAdaptiveIdChain($ax.adaptive.currentViewId); - var diagramObject = $ax.getObjectFromElementId(id); - if (diagramObject.generateCompound) return _matchImageCompound(diagramObject, id, viewIdChain, state); - else return _matchImage(id, diagramObject.images, viewIdChain, state); - }; - - var _getAdaptiveView = function(winWidth, winHeight) { - var _isViewOneGreaterThanTwo = function (view1, view2, winHeight) { - if (view1.size.width > view2.size.width) return true; - if (view1.size.width == view2.size.width) { - if (view2.size.height <= winHeight) return view1.size.height > view2.size.height && view1.size.height <= winHeight; - else return view1.size.height < view2.size.height; - } - return false; - }; - - var _isViewOneLessThanTwo = function(view1, view2) { - var width2 = view2.size.width || 1000000; // artificially large number - var height2 = view2.size.height || 1000000; - - var width1 = view1.size.width || 1000000; - var height1 = view1.size.height || 1000000; - - return width1 < width2 || (width1 == width2 && height1 < height2); - }; - - var _isWindowWidthGreaterThanViewWidth = function(view, width) { - return width >= view.size.width; - }; - - var _isWindowWidthLessThanViewWidth = function(view1, width) { - var viewWidth = view1.size.width || 1000000; - - return width <= viewWidth; - }; - - var greater = undefined; - var less = undefined; - - var defaultView = $ax.pageData.defaultAdaptiveView; - if (_isWindowWidthGreaterThanViewWidth(defaultView, winWidth, winHeight)) greater = defaultView; - less = defaultView; - for(var i = 0; i < _enabledViews.length; i++) { - var view = _enabledViews[i]; - if(_isWindowWidthGreaterThanViewWidth(view, winWidth, winHeight)) { - if(!greater || _isViewOneGreaterThanTwo(view, greater, winHeight)) greater = view; - } - if(_isWindowWidthLessThanViewWidth(view, winWidth, winHeight)) { - if(!less || _isViewOneLessThanTwo(view, less)) less = view; - } - } - return greater || less; - }; - - var _isAdaptiveInitialized = function() { - return typeof _idToView != 'undefined'; - }; - - - $ax.messageCenter.addMessageListener(function(message, data) { - //If the adaptive plugin hasn't been initialized yet then - //save the view to load so that it can get set when initialize occurs - if (message == 'switchAdaptiveView') { - if (!$axure.utils.isInPlayer()) return; - - var href = window.location.href.split('#')[0]; - var lastSlash = href.lastIndexOf('/'); - href = href.substring(lastSlash + 1); - if(href != data.src) return; - - var view = data.view == 'auto' ? undefined : (data.view == 'default' ? '' : data.view); - - if(!_isAdaptiveInitialized()) { - _initialViewToLoad = view; - } else _handleLoadViewId(view); - } else if (message == 'setAdaptiveViewForSize') { - if (!$axure.utils.isInPlayer()) return; - - _autoIsHandledBySidebar = true; - if(!_isAdaptiveInitialized()) { - _initialViewSizeToLoad = data; - } else _handleSetViewForSize(data.width, data.height); - } else if (message == 'getScale') { - if (!$axure.utils.isInPlayer()) return; - - var prevScaleN = data.prevScaleN; - var newScaleN = 1; - var contentOriginOffset = 0; - - var $body = $('body'); - $body.css('height', ''); - - if (data.scale != 0) { - var adjustScrollScale = false; - if ($('html').getNiceScroll().length == 0 && !MOBILE_DEVICE) { - //adding nicescroll so width is correct when getting scale - _addNiceScroll($('html'), { emulatetouch: false, horizrailenabled: false }); - adjustScrollScale = true; - } - - $('html').css('overflow-x', 'hidden'); - - var bodyWidth = $body.width(); - var isCentered = $body.css('position') == 'relative'; - - // screen width does not adjust on screen rotation for iOS (width is always shorter screen measurement) - var isLandscape = window.orientation != 0 && window.orientation != 180; - var mobileWidth = (IOS ? (isLandscape ? window.screen.height : window.screen.width) : window.screen.width) - data.panelWidthOffset; - var scaleN = newScaleN = (MOBILE_DEVICE ? mobileWidth : $(window).width()) / bodyWidth; - - if (data.scale == 2) { - var pageSize = $ax.public.fn.getPageSize(); - var hScaleN = (MOBILE_DEVICE ? data.viewportHeight : $(window).height()) / Math.max(1, pageSize.bottom); - if (hScaleN < scaleN) { - scaleN = newScaleN = hScaleN; - } - if (isCentered) contentOriginOffset = scaleN * (bodyWidth / 2); - } - - if ((SAFARI && IOS) || SHARE_APP) { - var pageSize = $ax.public.fn.getPageSize(); - $body.first().css('height', pageSize.bottom + 'px'); - } //else $body.css('height', $body.height() + 'px'); - - if (adjustScrollScale) { - _removeNiceScroll($('html')); - _addNiceScroll($('html'), { emulatetouch: false, horizrailenabled: false, cursorwidth: Math.ceil(6 / newScaleN) + 'px', cursorborder: 1 / newScaleN + 'px solid #fff', cursorborderradius: 5 / newScaleN + 'px' }); - } - } - var contentScale = { - scaleN: newScaleN, - prevScaleN: prevScaleN, - contentOriginOffset: contentOriginOffset, - clipToView: data.clipToView, - viewportHeight: data.viewportHeight, - viewportWidth: data.viewportWidth, - panelWidthOffset: data.panelWidthOffset, - scale: data.scale - }; - $axure.messageCenter.postMessage('setContentScale', contentScale); - - } else if (message == 'setDeviceMode') { - if (!$axure.utils.isInPlayer()) return; - - _isDeviceMode = data.device; - if (data.device) { - // FIXES firefox cursor not staying outside initial device frame border - // SAFARI needs entire content height so that trackpad can be disabled - //if (FIREFOX || (SAFARI && !IOS)) { - // var pageSize = $ax.public.fn.getPageSize(); - // $('html').css('height', pageSize.bottom + 'px'); - //} - - _removeNiceScroll($('html'), true); - if (!MOBILE_DEVICE) { - _addNiceScroll($('html'), { emulatetouch: true, horizrailenabled: false }, true); - $('html').addClass('mobileFrameCursor'); - $('html').css('cursor', 'url(resources/css/images/touch.cur), auto'); - $('html').css('cursor', 'url(resources/css/images/touch.svg) 32 32, auto'); - $('html').css('overflow-x', 'hidden'); - - if (IE) { - document.addEventListener("click", function () { - // IE still sometimes wants an argument here - this.activeElement.releasePointerCapture(); - }, false); - } - - if ($axure.browser.isEdge) { - document.addEventListener("pointerdown", function (e) { - this.activeElement.releasePointerCapture(e.pointerId); - }, false); - } - - $ax.dynamicPanelManager.initMobileScroll(); - } - - // Gives horizontal scroll to android in 100% (handled outside of iframe) - $('html').css('overflow-x', 'hidden'); - $('body').css('margin', '0px'); - $(function () { _setHorizontalScroll(false); }); - } else { - _removeNiceScroll($('html'), true); - $('html').css('overflow-x', ''); - $('html').css('cursor', ''); - //$('html').removeAttr('style'); - $('body').css('margin', ''); - $('html').removeClass('mobileFrameCursor'); - $(function () { _setHorizontalScroll(!data.scaleToWidth); }); - - $ax.dynamicPanelManager.initMobileScroll(); - } - } - }); - - var _isDeviceMode = false; - $ax.adaptive.isDeviceMode = function () { - return _isDeviceMode; - } - - var _isHtmlQuery = function ($container) { return $container.length > 0 && $container[0] == $('html')[0]; } - - var _removeNiceScroll = $ax.adaptive.removeNiceScroll = function ($container, blockResetScroll) { - if (!blockResetScroll) { - $container.scrollLeft(0); - $container.scrollTop(0); - } - var nS = $container.getNiceScroll(); - var emulateTouch = nS.length > 0 && nS[0].opt.emulateTouch; - nS.remove(); - //clean up nicescroll css - if (IE) $container.css({ '-ms-overflow-y': '', 'overflow-y': '', '-ms-overflow-style': '', '-ms-touch-action': '' }); - if (!emulateTouch) return; - if (_isHtmlQuery($container)) { - $('#scrollContainer').remove(); - $('#base').off('mouseleave.ax'); - } else { - $container.off('mouseleave.ax'); - } - } - - var _addNiceScrollExitDetector = function ($container) { - if (_isHtmlQuery($container)) { - - // add a fixed div the size of the frame that will not move as we scroll like html,body,#base,children - // so we are able to detect when the mouse leaves that frame area if there is no existing DOM element - var $scrollContainer = $("<div id='scrollContainer'></div>"); - var $body = $('body'); - $scrollContainer.css({ - 'position': 'fixed', - 'width': $body.width(), - 'height': $body.height() - }); - - // we want #base div to handle the event so that it bubbles up from the scrollContainer div which - // handles the bounds of the frame in case there was no previously exisiting child to bubble up the - // event or if the user has clicked on an existing child node to start the emulated touch scroll - var $base = $('#base'); - $base.on('mouseleave.ax', function (e) { - var nS = $container.getNiceScroll(); - for (var i = 0; i < nS.length; ++i) - nS[i].ontouchend(e); - }); - // need to prepend so it is first child in DOM and doesn't block mouse events to other children which - // would make them unable to scroll - $base.prepend($scrollContainer); - } else { - $container.on('mouseleave.ax', function (e) { - var nS = $container.getNiceScroll(); - for (var i = 0; i < nS.length; ++i) - nS[i].ontouchend(e); - }); - } - } - - var _addNiceScroll = $ax.adaptive.addNiceScroll = function ($container, options, blockResetScroll) { - if (!blockResetScroll) { - $container.scrollLeft(0); - $container.scrollTop(0); - } - $container.niceScroll(options); - // RP-581 add handling to stop scroll on mouse leave if enable cursor-drag scrolling like touch devices in desktop computer - if (options.emulatetouch) _addNiceScrollExitDetector($container); - //clean up nicescroll css so child scroll containers show scrollbars in IE - if (IE) $container.css({ '-ms-overflow-y': '', '-ms-overflow-style': '' }); - if(IOS) $container.css({ 'overflow-y': ''}); - } - - //given the element, find the container that's using nice scroll (including the element itself) - $ax.adaptive.getNiceScrollContainer = function(element) { - var parent = element; - while(parent) { - if($(parent).getNiceScroll().length > 0) return parent; - parent = parent.parentElement; - } - return undefined; - } - - - $ax.adaptive.updateMobileScrollOnBody = function () { - var niceScroll = $('html').getNiceScroll(); - if (niceScroll.length == 0) return; - niceScroll.resize(); - } - - var _setTrackpadHorizontalScroll = function (active) { - var preventScroll = function (e) { - if (Math.abs(e.wheelDeltaX) != 0) { - e.preventDefault(); - } - } - - if (!active) { - document.body.addEventListener("mousewheel", preventScroll, { passive: false }); - document.getElementById('html').addEventListener("mousewheel", preventScroll, { passive: false }); - } else { - document.body.removeEventListener("mousewheel", preventScroll, { passive: false }); - document.getElementById('html').removeEventListener("mousewheel", preventScroll, { passive: false }); - } - } - - var _setHorizontalScroll = function (active) { - var $body = $(document); - if (!active) { - $body.bind('scroll', function () { - if ($body.scrollLeft() !== 0) { - $body.scrollLeft(0); - } - }); - } else { - $body.unbind('scroll'); - } - } - - $ax.adaptive.setAdaptiveView = function(view) { - var viewIdForSitemapToUnderstand = view == 'auto' ? undefined : (view == 'default' ? '' : view); - - if(!_isAdaptiveInitialized()) { - _initialViewToLoad = viewIdForSitemapToUnderstand; - } else _handleLoadViewId(viewIdForSitemapToUnderstand); - }; - - $ax.adaptive.initialize = function() { - _views = $ax.pageData.adaptiveViews; - _idToView = {}; - - var useViews = $ax.document.configuration.useViews; - - if(_views && _views.length > 0) { - for(var i = 0; i < _views.length; i++) { - var view = _views[i]; - _idToView[view.id] = view; - if(useViews) _enabledViews[_enabledViews.length] = view; - } - - if(_autoIsHandledBySidebar && _initialViewSizeToLoad) _handleSetViewForSize(_initialViewSizeToLoad.width, _initialViewSizeToLoad.height); - else _handleLoadViewId(_initialViewToLoad); - } - - $axure.resize(function(e) { - _handleResize(); - $ax.postResize(e); //window resize fires after view changed - }); - }; - - var _handleLoadViewId = function (loadViewId, forceSwitchTo) { - if(typeof loadViewId != 'undefined') { - _setAuto(false); - _switchView(loadViewId != 'default' ? loadViewId : '', forceSwitchTo); - } else { - _setAuto(true); - _handleResize(forceSwitchTo); - } - }; - - var _handleSetViewForSize = function (width, height) { - var toView = _getAdaptiveView(width, height); - var toViewId = toView && toView.id; - _switchView(toViewId, "auto"); - }; - - $ax.adaptive.getSketchKey = function() { - return $ax.pageData.sketchKeys[$ax.adaptive.currentViewId || '']; - } -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/annotation.js b/web/main/static/resources/scripts/axure/annotation.js deleted file mode 100644 index f4ec9d1..0000000 --- a/web/main/static/resources/scripts/axure/annotation.js +++ /dev/null @@ -1,178 +0,0 @@ -// ******* Annotation MANAGER ******** // -$axure.internal(function($ax) { - var NOTE_SIZE = 10; - - var _annotationManager = $ax.annotation = {}; - - var _updateLinkLocations = $ax.annotation.updateLinkLocations = function(elementId) { - var textId = $ax.GetTextPanelId(elementId); - if(!textId) return; - - var rotation = $ax.getObjectFromElementId(elementId).style.rotation; - //we have to do this because webkit reports the post-transform position but when you set positions it's pre-transform - if(WEBKIT && rotation) { - //we can dynamiclly rotate a widget now, show need to remember the transform rather than just remove it - //here jquery.css will return 'none' if element is display none - var oldShapeTransform = document.getElementById(elementId).style['-webkit-transform']; - var oldTextTransform = document.getElementById(textId).style['-webkit-transform']; - $('#' + elementId).css('-webkit-transform', 'scale(1)'); - $('#' + textId).css('-webkit-transform', 'scale(1)'); - } - - $('#' + textId).find('div[id$="_ann"]').each(function(index, value) { - var elementId = value.id.replace('_ann', ''); - var $link = $('#' + elementId); - var annPos = $link.position(); - annPos.left += $link.width(); - //var annPos = $(value).position(); - var left = annPos.left;// - NOTE_SIZE; - var top = annPos.top - 5; - - $(value).css('left', left).css('top', top); - }); - - //undo the transform reset - if(WEBKIT && rotation) { - $('#' + elementId).css('-webkit-transform', oldShapeTransform || ''); - $('#' + textId).css('-webkit-transform', oldTextTransform || ''); - } - }; - - var _toggleAnnotationDialog = function (elementId, event) { - let win = $(window); - let scrollY = win.scrollTop(); - let scrollX = win.scrollLeft(); - - let x = event.pageX - scrollX; - let y = event.pageY - scrollY; - - let frameElement = window.frameElement; - let parent = window.parent; - //ann dialog is relative to mainFrame, exclude the mainFrame location so the notes shows up correctly in device mode - while(frameElement && frameElement.name !== 'mainFrame') { - let rect = frameElement.getBoundingClientRect(); - x += rect.x; - y += rect.y; - - if(!parent) break; - - frameElement = parent.frameElement; - parent = parent.parent; - } - - let messageData = { id: elementId, x: x, y: y } - if (!$axure.utils.isInPlayer()) messageData.page = $ax.pageData.notesData; - $ax.messageCenter.postMessage('toggleAnnDialog', messageData); - } - - $ax.annotation.initialize = function () { - _createFootnotes($ax('*'), true); - } - - var _createFootnotes = $ax.annotation.createFootnotes = function(query, create) { - if(!$ax.document.configuration.showAnnotations) return; - - var widgetNotes = $ax.pageData.notesData.widgetNotes; - if (widgetNotes) { - var ownerToFns = $ax.pageData.notesData.ownerToFns; - if(!$.isEmptyObject(ownerToFns)) { - query.each(function(dObj, elementId) { - var fns = ownerToFns[dObj.id]; - if (fns !== undefined) { - var elementIdQuery = $('#' + elementId); - if (dObj.type == 'hyperlink') { - var parentId = $ax.GetParentIdFromLink(elementId); - if (create) { - elementIdQuery.after("<div id='" + elementId + "_ann' class='annnote'>​</div>"); - appendFns($('#' + elementId + "_ann"), fns); - } - _updateLinkLocations(parentId); - } else { - if (create) { - elementIdQuery.after("<div id='" + elementId + "_ann' class='annnote'>​</div>"); - appendFns($('#' + elementId + "_ann"), fns); - } - _adjustIconLocation(elementId, dObj); - } - - if (create) { - $('#' + elementId + "_ann").click(function (e) { - _toggleAnnotationDialog(dObj.id, e); - return false; - }); - - var isVisible = true; - var isMaster = $ax.public.fn.IsReferenceDiagramObject(dObj.type); - if (isMaster) isVisible = dObj.visible; - else isVisible = $ax.visibility.IsIdVisible(elementId); - if (!isVisible) { - var ann = document.getElementById(elementId + "_ann"); - if (ann) $ax.visibility.SetVisible(ann, false); - } - } - } - }); - } - } - - function appendFns($parent, fns) { - for (var index = 0; index < fns.length; index++) { - $parent.append("<div class='annnotelabel' >" + fns[index] + "</div>"); - } - } - }; - - $ax.annotation.updateAllFootnotes = function () { - _createFootnotes($ax('*'), false); - } - - $ax.annotation.jQueryAnn = function(query) { - var elementIds = []; - query.each(function(diagramObject, elementId) { - if(diagramObject.annotation) elementIds[elementIds.length] = elementId; - }); - var elementIdSelectors = jQuery.map(elementIds, function(elementId) { return '#' + elementId + '_ann'; }); - var jQuerySelectorText = (elementIdSelectors.length > 0) ? elementIdSelectors.join(', ') : ''; - return $(jQuerySelectorText); - }; - - $(window.document).ready(function() { - //$ax.annotation.InitializeAnnotations($ax(function(dObj) { return dObj.annotation; })); - - $ax.messageCenter.addMessageListener(function(message, data) { - //If the annotations are being hidden via the Sitemap toggle button, hide any open dialogs - if(message == 'annotationToggle') { - if (data == true) { - $('div.annnote').show(); - } else { - $('div.annnote').hide(); - } - } - }); - }); - - //adjust annotation location to a element's top right corner - var _adjustIconLocation = $ax.annotation.adjustIconLocation = function(id, dObj) { - var ann = document.getElementById(id + "_ann"); - if(ann) { - var corners = $ax.public.fn.getCornersFromComponent(id); - var width = $(ann).width(); - var newTopRight = $ax.public.fn.vectorPlus(corners.relativeTopRight, corners.centerPoint); - //note size is 14x8, this is how rp calculated it as well - ann.style.left = (newTopRight.x - width) + "px"; - - var elementType = dObj ? dObj.type : $ax.getTypeFromElementId(id); - var yOffset = $ax.public.fn.IsTableCell(elementType) ? 0 : -8; - ann.style.top = (newTopRight.y + yOffset) + "px"; - } - - var ref = document.getElementById(id + "_ref"); - if(ref) { - if(!corners) corners = $ax.public.fn.getCornersFromComponent(id); - var newBottomRight = $ax.public.fn.vectorPlus(corners.relativeBottomRight, corners.centerPoint); - - ref.style.left = (newBottomRight.x - 8) + 'px'; - ref.style.top = (newBottomRight.y - 10) + 'px'; - } - } -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/axQuery.js b/web/main/static/resources/scripts/axure/axQuery.js deleted file mode 100644 index 9108dfd..0000000 --- a/web/main/static/resources/scripts/axure/axQuery.js +++ /dev/null @@ -1,407 +0,0 @@ -$axure = function(query) { - return $axure.query(query); -}; - -// ******* AxQuery and Page metadata ******** // -(function() { - var $ax = function() { - var returnVal = $axure.apply(this, arguments); - var axFn = $ax.fn; - for (var key in axFn) { - returnVal[key] = axFn[key]; - } - - return returnVal; - }; - - $ax.public = $axure; - $ax.fn = {}; - - $axure.internal = function(initFunction) { - //Attach messagecenter to $ax object so that it can be used in viewer.js, etc in internal scope - if(!$ax.messageCenter) $ax.messageCenter = $axure.messageCenter; - - return initFunction($ax); - }; - - var _lastFiredResize = 0; - var _resizeFunctions = []; - var _lastTimeout; - var _fireResize = function() { - if (_lastTimeout) window.clearTimeout(_lastTimeout); - _lastTimeout = undefined; - _lastFiredResize = new Date().getTime(); - for(var i = 0; i < _resizeFunctions.length; i++) _resizeFunctions[i](); - }; - - $axure.resize = function(fn) { - if(fn) _resizeFunctions[_resizeFunctions.length] = fn; - else $(window).resize(); - }; - - $(window).resize(function() { - var THRESHOLD = 50; - _updateWindowInfo(); - var now = new Date().getTime(); - if(now - _lastFiredResize > THRESHOLD) { - _fireResize(); - } else if(!_lastTimeout) { - _lastTimeout = window.setTimeout(_fireResize, THRESHOLD); - } - }); - - $(window).scroll(function () { - _updateWindowInfo(); - }); - - var _windowInfo; - var _updateWindowInfo = $axure.updateWindowInfo = function () { - var win = {}; - var jWin = $(window); - var scrollWin = $('#ios-safari-html').length > 0 ? $('#ios-safari-html') : jWin; - win.width = jWin.width(); - win.height = jWin.height(); - win.scrollx = scrollWin.scrollLeft(); - win.scrolly = scrollWin.scrollTop(); - _windowInfo = win; - }; - $ax.getWindowInfo = function () { - if(!_windowInfo) _updateWindowInfo(); - return _windowInfo; - }; - - - window.$obj = function(id) { - return $ax.getObjectFromElementId(id); - }; - - window.$id = function(obj) { - return obj.scriptIds[0]; - }; - - window.$jobj = function(id) { - return $(document.getElementById(id)); - }; - - window.$jobjAll = function(id) { - return $addAll($jobj(id), id); - }; - - window.$addAll = function(jobj, id) { - return jobj.add($jobj(id + '_ann')).add($jobj(id + '_ref')); - }; - - $ax.INPUT = function(id) { return id + "_input"; }; - $ax.IsImageFocusable = function (type) { return $ax.public.fn.IsImageBox(type) || $ax.public.fn.IsVector(type) || $ax.public.fn.IsTreeNodeObject(type) || $ax.public.fn.IsTableCell(type); }; - $ax.IsTreeNodeObject = function (type) { return $ax.public.fn.IsTreeNodeObject(type); }; - $ax.IsSelectionButton = function (type) { return $ax.public.fn.IsCheckBox(type) || $ax.public.fn.IsRadioButton(type); }; - - var _fn = {}; - $axure.fn = _fn; - $axure.fn.jQuery = function() { - var elements = this.getElements(); - return $(elements); - }; - $axure.fn.$ = $axure.fn.jQuery; - - var _query = function(query, queryArg) { - var returnVal = {}; - var _axQueryObject = returnVal.query = { }; - _axQueryObject.filterFunctions = []; - - if (query == '*') { - _axQueryObject.filterFunctions[0] = function() { return true; }; - } else if (typeof(query) === 'function') { - _axQueryObject.filterFunctions[0] = query; - } else { - var firstString = $.trim(query.toString()); - if (firstString.charAt(0) == '@') { - _axQueryObject.filterFunctions[0] = function(diagramObject) { - return diagramObject.label == firstString.substring(1); - }; - } else if (firstString.charAt(0) == '#') { - _axQueryObject.elementId = firstString.substring(1); - } else { - if (firstString == 'label') { - _axQueryObject.filterFunctions[0] = function(diagramObject) { - return queryArg instanceof Array && queryArg.indexOf(diagramObject.label) > 0 || - queryArg instanceof RegExp && queryArg.test(diagramObject.label) || - diagramObject.label == queryArg; - }; - } else if(firstString == 'elementId') { - _axQueryObject.filterFunctions[0] = function(diagramObject, elementId) { - return queryArg instanceof Array && queryArg.indexOf(elementId) > 0 || - elementId == queryArg; - }; - } - } - } - - var axureFn = $axure.fn; - for (var key in axureFn) { - returnVal[key] = axureFn[key]; - } - return returnVal; - }; - $axure.query = _query; - - var _getFilterFnFromQuery = function(query) { - var filter = function(diagramObject, elementId) { - // Non diagram objects are allowed to be queryed, such as text inputs. - if (diagramObject && !$ax.public.fn.IsReferenceDiagramObject(diagramObject.type) && !document.getElementById(elementId)) return false; - var retVal = true; - for(var i = 0; i < query.filterFunctions.length && retVal; i++) { - retVal = query.filterFunctions[i](diagramObject, elementId); - } - return retVal; - }; - return filter; - }; - - $ax.public.fn.filter = function(query, queryArg) { - var returnVal = _query(query, queryArg); - - if(this.query.elementId) returnVal.query.elementId = this.query.elementId; - - //If there is already a function, offset by 1 when copying other functions over. - var offset = returnVal.query.filterFunctions[0] ? 1 : 0; - - //Copy all functions over to new array. - for(var i = 0; i < this.query.filterFunctions.length; i++) returnVal.query.filterFunctions[i+offset] = this.query.filterFunctions[i]; - - //Functions are in reverse order now - returnVal.query.filterFunctions.reverse(); - - return returnVal; - }; - - $ax.public.fn.each = function(fn) { - var filter = _getFilterFnFromQuery(this.query); - var elementIds = this.query.elementId ? [this.query.elementId] : $ax.getAllElementIds(); - for (var i = 0; i < elementIds.length; i++) { - var elementId = elementIds[i]; - var diagramObject = $ax.getObjectFromElementId(elementId); - if (filter(diagramObject, elementId)) { - fn.apply(diagramObject, [diagramObject, elementId]); - } - } - }; - - $ax.public.fn.getElements = function() { - var elements = []; - this.each(function(dObj, elementId) { - var elementById = document.getElementById(elementId); - if(elementById) elements[elements.length] = elementById; - }); - return elements; - }; - - $ax.public.fn.getElementIds = function() { - var elementIds = []; - this.each(function(dObj, elementId) { elementIds[elementIds.length] = elementId; }); - return elementIds; - }; - - // Deep means to keep getting parents parent until at the root parent. Parent is then an array instead of an id. - // Filter options: layer, rdo, repeater, item, dynamicPanel, state - $ax.public.fn.getParents = function (deep, filter) { - if(filter == '*') filter = ['layer', 'rdo', 'repeater', 'item', 'dynamicPanel', 'state']; - var elementIds = this.getElementIds(); - var parentIds = []; - - var getParent = function(elementId) { - var containerIndex = elementId.indexOf('_container'); - if(containerIndex !== -1) elementId = elementId.substring(0, containerIndex); - if(elementId.indexOf('_text') !== -1) elementId = $ax.GetShapeIdFromText(elementId); - - // Check repeater item before layer, because repeater item detects it's parent layer, but wants to go directly to it's repeater first. - // if repeater item, then just return repeater - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - var itemNum = $ax.repeater.getItemIdFromElementId(elementId); - var parentRepeater = $ax.getParentRepeaterFromScriptId(scriptId); - - // scriptId is item or repeater itself - if (parentRepeater == scriptId) { - // If you are repeater item, return your repeater - if (itemNum) return filter.indexOf('repeater') != -1 ? scriptId : getParent(scriptId); - // Otherwise you are actually at repeater, clean parentRepeater, or else you loop - parentRepeater = undefined; - } - - // Layer only references it if it is a direct layer to it - var parent = $ax.getLayerParentFromElementId(elementId); - // If layer is allowed we found parent, otherwise ignore and keep climbing - if (parent) return filter.indexOf('layer') != -1 ? parent : getParent(parent); - - // if state, then just return panel - if(scriptId.indexOf('_state') != -1) { - var panelId = $ax.repeater.createElementId(scriptId.split('_')[0], itemNum); - // If dynamic panel is allowed we found parent, otherwise ignore and keep climbing - return filter.indexOf('dynamicPanel') != -1 ? panelId : getParent(panelId); - } - - var parentType = ''; - if(parentRepeater) { - parentType = 'item'; - parent = $ax.repeater.createElementId(parentRepeater, itemNum); - } - - var masterPath = $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(elementId)); - masterPath.pop(); - if(masterPath.length > 0) { - var masterId = $ax.getElementIdFromPath(masterPath, { itemNum: itemNum }, true); - if(!masterId) return undefined; - var masterRepeater = $ax.getParentRepeaterFromElementId($ax.repeater.getScriptIdFromElementId(masterId)); - if(!parentRepeater || masterRepeater) { - parentType = 'rdo'; - parent = masterId; - } - } - - var obj = $obj(elementId); - var parentDynamicPanel = obj.parentDynamicPanel; - if(parentDynamicPanel) { - // Make sure the parent if not parentRepeater, or dynamic panel is also in that repeater - // If there is a parent master, the dynamic panel must be in it, otherwise parentDynamicPanel would be undefined. - var panelPath = masterPath; - panelPath[panelPath.length] = parentDynamicPanel; - panelId = $ax.getElementIdFromPath(panelPath, { itemNum: itemNum }, true); - if(!panelId) return undefined; - var panelRepeater = $ax.getParentRepeaterFromElementId(panelId); - if(!parentRepeater || panelRepeater) { - parentType = 'state'; - parent = panelId + '_state' + obj.panelIndex; - } - } - - // If at top or parent type is desired, then return parent, otherwise keep climbing - return !parent || filter.indexOf(parentType) != -1 ? parent : getParent(parent); - }; - - for (var i = 0; i < elementIds.length; i++) { - var elementId = elementIds[i]; - if ((elementId || elementId === 0) && elementId !== "undefined") { - var parent = getParent(elementId); - if (deep) { - var parents = []; - while (parent) { - parents[parents.length] = parent; - // If id is not a valid object, you are either repeater item or dynamic panel state - //if(!$obj(parent)) parent = $ax.visibility.getWidgetFromContainer($jobj(parent).parent().attr('id')); - - parent = getParent(parent); - } - parent = parents; - } - parentIds[parentIds.length] = parent; - } - } - return parentIds; - }; - - // Get the path to the child, where non leaf nodes can be masters, layers, dynamic panels, and repeaters. - $ax.public.fn.getChildren = function(deep, ignoreUnplaced) { // ignoreUnplaced should probably be the default, but when that is done a full audit of usages should be done - var elementIds = this.getElementIds(); - var children = []; - - var getChildren = function (elementId) { - var obj = $obj(elementId); - //if(!obj) return undefined; - - var isRepeater = obj && obj.type == $ax.constants.REPEATER_TYPE; - if (isRepeater && $ax.repeater.getScriptIdFromElementId(elementId) != elementId) { - //prevent repeater items from being marked as isRepeater - //TODO: evaluate changing the naming convention to be more like panel states which don't seem to have this problem - obj = undefined; - isRepeater = false; - } - var isDynamicPanel = obj && obj.type == $ax.constants.DYNAMIC_PANEL_TYPE; - //var isLayer = obj.type == $ax.constants.LAYER_TYPE; - //var isMaster = obj.type == $ax.constants.MASTER_TYPE || obj.type == $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE; - - var isMenu = obj && obj.type == $ax.constants.MENU_OBJECT_TYPE; - var isTreeNode = obj && obj.type == $ax.constants.TREE_NODE_OBJECT_TYPE; - //var isTable = obj.type == $ax.constants.TABLE_TYPE; - //var isCompoundVector = obj.type == $ax.constants.VECTOR_SHAPE_TYPE && obj.generateCompound; - - //if (isRepeater || isDynamicPanel || isLayer || isMaster || isMenu || isTreeNode || isTable) {// || isCompoundVector) { - // Find parent that children should be pulled from. Default is just the elementId query (used by table and master) - var parent = $jobj(elementId); - if(isRepeater) { - parent = $(); - var itemIds = $ax.getItemIdsForRepeater(elementId); - for(var itemIndex = 0; itemIndex < itemIds.length; itemIndex++) parent = parent.add($jobj($ax.repeater.createElementId(elementId, itemIds[itemIndex]))); - } else if(isDynamicPanel) { - // Really only need to do active state probably... - parent = $jobj(elementId).children(); - // Get through all containers - while ($(parent[0]).attr('id').indexOf('container') != -1) parent = parent.children(); - // Now at states, but want states content - parent = parent.children(); - } else if(isTreeNode) parent = $jobj($ax.repeater.applySuffixToElementId(elementId, '_children')); - - // Menu doesn't want all children, only tables and menus, so it must be handled specially - var children = isMenu ? parent.children('.ax_table').add(parent.children('.ax_menu')) : parent.children(); - children = $ax.visibility.getRealChildren(_fixForBasicLinks(children)); - - // For tree nodes you want the the button shape contained by the elementQuery too - if(isTreeNode) { - var treeNodeChildren = $jobj(elementId).children(); - for(var treeNodeIndex = 0; treeNodeIndex < treeNodeChildren.length; treeNodeIndex++) { - var treeNodeChild = $(treeNodeChildren[treeNodeIndex]); - var childObj = $obj(treeNodeChild.attr('id')); - if (childObj && $ax.public.fn.IsVector(childObj.type)) children = children.add(treeNodeChild); - } - } - - - var childrenIds = []; - for(var childIndex = 0; childIndex < children.length; childIndex++) { - var childObj = $(children[childIndex]); - var id = childObj.attr('id'); - if(typeof(id) == 'undefined' && childObj.is('a')) id = $(childObj.children()[0]).attr('id'); - // Ignore annotations and any other children that are not elements - if (id.split('_').length > 1) continue; - // Ignore Unplaced - if(ignoreUnplaced && $ax.visibility.isScriptIdLimbo($ax.repeater.getScriptIdFromElementId(id))) continue; - childrenIds.push(id); - } - - if(deep) { - var childObjs = []; - for(var i = 0; i < childrenIds.length; i++) { - var childId = childrenIds[i]; - childObjs[i] = { id: childId, children: getChildren(childId) }; - } - childrenIds = childObjs; - } - - return childrenIds; - //} - - //return undefined; - }; - - for(var i = 0; i < elementIds.length; i++) { - var elementId = elementIds[i]; - //if the state is passed in, look for children in the content element - if (elementId.indexOf('_state') > -1 && elementId.indexOf('_content') < 0) elementId = elementId + '_content'; - children[children.length] = { id: elementId, children: getChildren(elementId)}; - } - return children; - }; - - var _fixForBasicLinks = function(query) { - var hasBasicLinks = query.filter('.basiclink').length > 0; - if(!hasBasicLinks) return query; - - var retval = $(); - for(var i = 0; i < query.length; i++) { - var child = $(query[i]); - if(child.hasClass('basiclink')) retval = retval.add(child.children()); - else retval = retval.add(child); - } - return retval; - }; - -})(); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/axQuery.std.js b/web/main/static/resources/scripts/axure/axQuery.std.js deleted file mode 100644 index d92b477..0000000 --- a/web/main/static/resources/scripts/axure/axQuery.std.js +++ /dev/null @@ -1,1864 +0,0 @@ -// ******* AxQuery Plugins ******** // - -$axure.internal(function($ax) { - $ax.constants = {}; - - $ax.constants.TABLE_TYPE = 'table'; - $ax.constants.MENU_OBJECT_TYPE = 'menuObject'; - $ax.constants.MASTER_TYPE = 'master'; - $ax.constants.PAGE_TYPE = 'page'; - $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE = 'referenceDiagramObject'; - $ax.constants.REPEATER_TYPE = 'repeater'; - $ax.constants.DYNAMIC_PANEL_TYPE = 'dynamicPanel'; - $ax.constants.LAYER_TYPE = 'layer'; - $ax.constants.TEXT_BOX_TYPE = 'textBox'; - $ax.constants.TEXT_AREA_TYPE = 'textArea'; - $ax.constants.LIST_BOX_TYPE = 'listBox'; - $ax.constants.COMBO_BOX_TYPE = 'comboBox'; - $ax.constants.CHECK_BOX_TYPE = 'checkbox'; - $ax.constants.RADIO_BUTTON_TYPE = 'radioButton'; - $ax.constants.BUTTON_TYPE = 'button'; //html button - $ax.constants.IMAGE_MAP_REGION_TYPE = 'imageMapRegion'; - $ax.constants.IMAGE_BOX_TYPE = 'imageBox'; - $ax.constants.VECTOR_SHAPE_TYPE = 'vectorShape'; - $ax.constants.SNAPSHOT_TYPE = 'screenshot'; - $ax.constants.TREE_NODE_OBJECT_TYPE = 'treeNodeObject'; - $ax.constants.TABLE_CELL_TYPE = 'tableCell'; - $ax.constants.VERTICAL_LINE_TYPE = 'verticalLine'; - $ax.constants.HORIZONTAL_LINE_TYPE = 'horizontalLine'; - $ax.constants.INLINE_FRAME_TYPE = 'inlineFrame'; - $ax.constants.CONNECTOR_TYPE = 'connector'; - $ax.constants.ALL_TYPE = '*'; - - $ax.constants.TEXT_TYPE = 'richTextPanel'; - $ax.constants.LINK_TYPE = 'hyperlink'; - - // TODO: Need solid passo f this. Constants should be able to bemade local, may need some public lists or something. - // public.fn function should take not arg and use this. May need some $ax.IsType fuctions that will take a type arg and be static - $ax.public.fn.IsTable = function (type) { return type == $ax.constants.TABLE_TYPE; } - $ax.public.fn.IsMenuObject = function (type) { return type == $ax.constants.MENU_OBJECT_TYPE; } - $ax.public.fn.IsMaster = function (type) { return type == $ax.constants.MASTER_TYPE; } - $ax.public.fn.IsPage = function (type) { return type == $ax.constants.PAGE_TYPE; } - $ax.public.fn.IsReferenceDiagramObject = function (type) { return type == $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE; } - $ax.public.fn.IsRepeater = function (type) { return type == $ax.constants.REPEATER_TYPE; } - $ax.public.fn.IsDynamicPanel = $ax.IsDynamicPanel = function (type) { return type == $ax.constants.DYNAMIC_PANEL_TYPE; } - $ax.public.fn.IsLayer = $ax.IsLayer = function (type) { return type == $ax.constants.LAYER_TYPE; } - $ax.public.fn.IsTextBox = function (type) { return type == $ax.constants.TEXT_BOX_TYPE; } - $ax.public.fn.IsTextArea = function (type) { return type == $ax.constants.TEXT_AREA_TYPE; } - $ax.public.fn.IsListBox = function (type) { return type == $ax.constants.LIST_BOX_TYPE; } - $ax.public.fn.IsComboBox = function (type) { return type == $ax.constants.COMBO_BOX_TYPE; } - $ax.public.fn.IsCheckBox = function (type) { return type == $ax.constants.CHECK_BOX_TYPE; } - $ax.public.fn.IsRadioButton = function (type) { return type == $ax.constants.RADIO_BUTTON_TYPE; } - $ax.public.fn.IsButton = function (type) { return type == $ax.constants.BUTTON_TYPE; } - $ax.public.fn.IsIamgeMapRegion = function (type) { return type == $ax.constants.IMAGE_MAP_REGION_TYPE; } - $ax.public.fn.IsImageBox = function (type) { return type == $ax.constants.IMAGE_BOX_TYPE; } - $ax.public.fn.IsVector = function (type) { return type == $ax.constants.VECTOR_SHAPE_TYPE; } - $ax.public.fn.IsSnapshot = function (type) { return type == $ax.constants.SNAPSHOT_TYPE; } - $ax.public.fn.IsTreeNodeObject = function (type) { return type == $ax.constants.TREE_NODE_OBJECT_TYPE; } - $ax.public.fn.IsTableCell = function (type) { return type == $ax.constants.TABLE_CELL_TYPE; } - $ax.public.fn.IsInlineFrame = function (type) { return type == $ax.constants.INLINE_FRAME_TYPE; } - $ax.public.fn.IsConnector = function (type) { return type == $ax.constants.CONNECTOR_TYPE; } - $ax.public.fn.IsContainer = function (type) { return type== $ax.constants.VECTOR_SHAPE_TYPE || type == $ax.constants.TABLE_TYPE || type == $ax.constants.MENU_OBJECT_TYPE || type == $ax.constants.TREE_NODE_OBJECT_TYPE; } - - var PLAIN_TEXT_TYPES = [$ax.constants.TEXT_BOX_TYPE, $ax.constants.TEXT_AREA_TYPE, $ax.constants.LIST_BOX_TYPE, - $ax.constants.COMBO_BOX_TYPE, $ax.constants.CHECK_BOX_TYPE, $ax.constants.RADIO_BUTTON_TYPE, $ax.constants.BUTTON_TYPE]; - - $ax.public.fn.IsResizable = function (type) { return $.inArray(type, RESIZABLE_TYPES) !== -1; } - var RESIZABLE_TYPES = [ - $ax.constants.BUTTON_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE, $ax.constants.IMAGE_BOX_TYPE, $ax.constants.IMAGE_MAP_REGION_TYPE, - $ax.constants.INLINE_FRAME_TYPE, $ax.constants.LAYER_TYPE, $ax.constants.LIST_BOX_TYPE, $ax.constants.COMBO_BOX_TYPE, - $ax.constants.VECTOR_SHAPE_TYPE, $ax.constants.TEXT_AREA_TYPE, $ax.constants.TEXT_BOX_TYPE, $ax.constants.SNAPSHOT_TYPE - ]; - - $ax.public.fn.IsSelectionButton = function(type) { - return type == $ax.constants.RADIO_BUTTON_TYPE || type == $ax.constants.CHECK_BOX_TYPE; - }; - - $ax.public.fn.SupportsRichText = function() { - var obj = $obj(this.getElementIds()[0]); - // Catch root tree nodes as they are not supported. - if(obj.type == $ax.constants.TREE_NODE_OBJECT_TYPE) return obj.friendlyType == 'Tree Node'; - // Do the same for tree node icons maybe? - - return $.inArray(obj.type, SUPPORTS_RICH_TEXT_TYPES) != -1; - } - var SUPPORTS_RICH_TEXT_TYPES = [$ax.constants.CHECK_BOX_TYPE, $ax.constants.RADIO_BUTTON_TYPE, - $ax.constants.IMAGE_BOX_TYPE, $ax.constants.VECTOR_SHAPE_TYPE, $ax.constants.TABLE_CELL_TYPE, $ax.constants.CONNECTOR_TYPE]; - - var _addJQueryFunction = function(name) { - $ax.public.fn[name] = function() { - var val = $.fn[name].apply(this.jQuery(), arguments); - return arguments[0] ? this : val; - }; - }; - var _jQueryFunctionsToAdd = ['text', 'val', 'css']; - for (var jqueryFunctionIndex = 0; jqueryFunctionIndex < _jQueryFunctionsToAdd.length; jqueryFunctionIndex++) _addJQueryFunction(_jQueryFunctionsToAdd[jqueryFunctionIndex]); - - - // var _addJQueryEventFunction = function(name) { - // $ax.public.fn[name] = function() { - // $.fn[name].apply(this.jQuery(), arguments); - // return this; - // }; - // }; - - // var _addJQueryEventFunction = function(name) { - // $ax.public.fn[name] = (function(nn) { - // return function() { - // $.fn[nn].apply(this.jQuery(), arguments); - // return this; - // }; - // })(name); - // }; - - var _addJQueryEventFunction = function(name) { - $ax.public.fn[name] = function() { - //With Martin - No idea why this is necessary. We tried encapsulating the function thinking it was related to closure (above), - //but that didn't fix the problem. If we don't add this Repeaters will give "Uncaught TypeError: Object #<Object> has no method 'apply'" - //here (but Indeterminately, often on larger/slower Repeaters) because it is Undefined. However it seems the catch is never hit - //if we surround the statement with the try/catch. Perhaps the try/catch block creates a scope or closure. - try { - $.fn[name].apply(this.jQuery(), arguments); - } catch(e) { - console.log("Couldn't find the event: " + name); - } - - return this; - }; - }; - var _jQueryEventFunctionsToAdd = ['click', 'mouseenter', 'mouseleave', 'bind']; - for(var jqueryEventIndex = 0; jqueryEventIndex < _jQueryEventFunctionsToAdd.length; jqueryEventIndex++) _addJQueryEventFunction(_jQueryEventFunctionsToAdd[jqueryEventIndex]); - - - $ax.public.fn.openLink = function(url, includeVariables) { - this.jQuery().each(function() { - if(!($(this).is('iframe'))) { - return; - } - - var objIframe = $(this).get(0); - - $ax.navigate({ - url: url, - target: "frame", - includeVariables: includeVariables, - frame: objIframe - }); - }); - - return this; - }; - - $ax.public.fn.SetPanelState = function(stateNumber, options, showWhenSet) { - - var animateInInfo = _getAnimateInfo(options && options.animateIn, 500); - var animateOutInfo = _getAnimateInfo(options && options.animateOut, 500); - - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - if ($ax.public.fn.IsDynamicPanel($ax.getTypeFromElementId(elementId))) { - var stateName = $ax.visibility.GetPanelStateId(elementId, Number(stateNumber) - 1); - var wasVisible = $ax.visibility.IsIdVisible(elementId); - // If compressing because you are fit to content and the change of state may change size, must be before the change. - if(options.compress && $ax.dynamicPanelManager.isIdFitToContent(elementId) && wasVisible) { - $ax.dynamicPanelManager.compressDelta(elementId, $ax.visibility.GetPanelState(elementId), stateName, options.vertical, options.compressEasing, options.compressDuration); - } - $ax.visibility.SetPanelState(elementId, stateName, animateOutInfo.easingType, animateOutInfo.direction, animateOutInfo.duration, - animateInInfo.easingType, animateInInfo.direction, animateInInfo.duration, showWhenSet); - // If compressing because of a show, must be after state is set. - if(options.compress && !wasVisible && showWhenSet) { - $ax.dynamicPanelManager.compressToggle(elementId, options.vertical, true, options.compressEasing, options.compressDuration); - } - } - } - - return this; - }; - - $ax.public.fn.show = function(options, eventInfo) { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - - var lightboxId = $ax.repeater.applySuffixToElementId(elementId, '_lightbox'); - var lightbox = $jobj(lightboxId); - if(options && options.showType == 'lightbox') { - $ax.flyoutManager.unregisterPanel(elementId, true); - // Add lightbox if there isn't one - if(lightbox.length == 0) { - lightbox = $('<div></div>'); - lightbox.attr('id', lightboxId); - var color = 'rgb(' + options.lightbox.r + ',' + options.lightbox.g + ',' + options.lightbox.b + ')'; - lightbox.css({ - position: 'fixed', - left: '0px', - top: '0px', - width: '10000px', - height: '10000px', - 'background-color': color, - opacity: options.lightbox.a / 255 - }); - - var parents = $ax('#' + elementId).getParents(true, ['dynamicPanel'])[0]; - var fixedParentPanelId = undefined; - for(var j = 0; j < parents.length; j++) { - var parentId = parents[j]; - if($jobj(parentId).css('z-index') != 'auto' || $ax.features.supports.mobile) { - fixedParentPanelId = parents[j]; - break; - } - } - - if(!fixedParentPanelId) $('#base').append(lightbox); - else $jobj(fixedParentPanelId).append(lightbox); - - var wasVisible = $ax.visibility.IsIdVisible(elementId); - - (function(lightbox, query) { - $ax.event.attachClick(lightbox, function() { - $ax.action.addAnimation(elementId, $ax.action.queueTypes.fade, function() { - if(!wasVisible) query.hide(); - else $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.fade); - lightbox.remove(); - }); - }); - })(lightbox, this); - } - $ax.legacy.BringToFront(lightboxId, true); - $ax.legacy.BringToFront(elementId, true); - } else if(options && options.showType == 'flyout') { - // Remove lightbox if there is one - lightbox.remove(); - - var src = eventInfo.thiswidget; - var target = $ax.getWidgetInfo(elementId); - var rects = {}; - if(src.valid) rects.src = $ax.geometry.genRect(src, true); - if(target.valid) rects.target = $ax.geometry.genRect(target, true); - $ax.flyoutManager.registerFlyout(rects, elementId, eventInfo.srcElement); - //$ax.style.AddRolloverOverride(elementId); - $ax.legacy.BringToFront(elementId); - } else { - // Remove lightbox, unregister flyout - lightbox.remove(); - $ax.flyoutManager.unregisterPanel(elementId, true); - } - _setVisibility(elementId, true, options); - } - - return this; - }; - - var _getAnimateInfo = function (options, defaultDuration, useHide) { - var durationOption, easingOption, animationOption; - - if(options) { - if (useHide) { - durationOption = options.durationHide; - easingOption = options.easingHide; - animationOption = options.animationHide; - } else { - durationOption = options.duration; - easingOption = options.easing; - animationOption = options.animation; - } - if (animationOption == 'none') animationOption = 'swing'; - } else { - durationOption = defaultDuration; - easingOption = 'none', - animationOption = 'swing'; - } - var animateInfo = { duration: durationOption }; - switch (easingOption) { - case 'fade': - animateInfo.easingType = 'fade'; - animateInfo.direction = ''; - break; - case 'slideLeft': - animateInfo.easingType = animationOption; - animateInfo.direction = 'left'; - break; - case 'slideRight': - animateInfo.easingType = animationOption; - animateInfo.direction = 'right'; - break; - case 'slideUp': - animateInfo.easingType = animationOption; - animateInfo.direction = 'up'; - break; - case 'slideDown': - animateInfo.easingType = animationOption; - animateInfo.direction = 'down'; - break; - case 'flipLeft': - animateInfo.easingType = 'flip'; - animateInfo.direction = 'left'; - break; - case 'flipRight': - animateInfo.easingType = 'flip'; - animateInfo.direction = 'right'; - break; - case 'flipUp': - animateInfo.easingType = 'flip'; - animateInfo.direction = 'up'; - break; - case 'flipDown': - animateInfo.easingType = 'flip'; - animateInfo.direction = 'down'; - break; - default: - animateInfo.easingType = 'none'; - animateInfo.direction = ''; - } - - return animateInfo; - }; - - $ax.public.fn.hide = function(options) { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; -// var wasShown = $ax.visibility.IsIdVisible(elementId); - _setVisibility(elementId, false, options, true); - } - - return this; - }; - - $ax.public.fn.toggleVisibility = function(options) { - var elementIds = this.getElementIds(); - - for (var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - var show = !$ax.visibility.IsIdVisible(elementId); - _setVisibility(elementId, show, options, !show); - } - - return this; - }; - - var _setVisibility = function (elementId, value, options, useHide) { - var animateInfo = _getAnimateInfo(options, 0, useHide); - - var wasShown = $ax.visibility.IsIdVisible(elementId); - var compress = options && options.showType == 'compress' && wasShown != value; - if (compress) $ax.dynamicPanelManager.compressToggle(elementId, options.vertical, value, options.compressEasing, options.compressDuration); - - var onComplete = function () { - $ax.dynamicPanelManager.fitParentPanel(elementId); - }; - $ax.visibility.SetWidgetVisibility(elementId, { - value: value, - easing: animateInfo.easingType, - direction: animateInfo.direction, - duration: animateInfo.duration, - animation: animateInfo.animation, - fire: true, - onComplete: onComplete - }); - - if(options && options.bringToFront) $ax.legacy.BringToFront(elementId); - }; - - $ax.public.fn.setOpacity = function(opacity, easing, duration) { - if(!easing || ! duration) { - easing = 'none'; - duration = 0; - } - - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - var onComplete = function() { - $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.fade); - }; - - var query = $jobj(elementId); - if(duration == 0 || easing == 'none') { - query.css('opacity', opacity); - onComplete(); - } else query.animate({ opacity: opacity }, { duration: duration, easing: easing, queue: false, complete: onComplete }); - } - } - //move one widget. I didn't combine moveto and moveby, since this is in .public, and separate them maybe more clear for the user - var _move = function (elementId, x, y, options, moveTo) { - if(!options.easing) options.easing = 'none'; - if(!options.duration) options.duration = 500; - var obj = $obj(elementId); - - // Layer move using container now. - if($ax.public.fn.IsLayer(obj.type)) { - $ax.move.MoveWidget(elementId, x, y, options, moveTo, - function () { - if(options.onComplete) options.onComplete(); - $ax.dynamicPanelManager.fitParentPanel(elementId); - }, false); - } else { - var xDelta = x; - var yDelta = y; - if (moveTo) { - var jobj = $jobj(elementId); - var left = $ax.getNumFromPx(jobj.css('left')); - var top = $ax.getNumFromPx(jobj.css('top')); - xDelta = x - left; - yDelta = y - top; - } - $ax.move.MoveWidget(elementId, xDelta, yDelta, options, false, - function () { $ax.dynamicPanelManager.fitParentPanel(elementId); }, true); - } - }; - - $ax.public.fn.getCursorOffset = function (elementId) { - var cursorOffset = { x: 0, y: 0 }; - - var element = $ax('#' + elementId); - var dynamicPanelParents = element.getParents(true, 'dynamicPanel')[0] || []; - // repeater can be only one - var repeaterParents = element.getParents(false, 'repeater'); - var relativeLocationParents = dynamicPanelParents.concat(repeaterParents); - var getParentOffset = function (elementId, parentId) { - var parentType = $ax.getTypeFromElementId(parentId); - if ($ax.public.fn.IsDynamicPanel(parentType)) { - return $ax('#' + parentId).offsetLocation(); - } - if ($ax.public.fn.IsRepeater(parentType)) { - return $ax.repeater.getRepeaterElementOffset(parentId, elementId); - } - return { x: 0, y: 0 }; - }; - for (var i = 0; i < relativeLocationParents.length; i++) { - var parentId = relativeLocationParents[i]; - if (parentId) { - var parentOffset = getParentOffset(elementId, parentId); - cursorOffset.x += parentOffset.x; - cursorOffset.y += parentOffset.y; - } - } - return cursorOffset; - } - - - $ax.public.fn.moveTo = function (x, y, options) { - var elementIds = this.getElementIds(); - for(var index = 0; index < elementIds.length; index++) { - _move(elementIds[index], x, y, options, true); - } - - return this; - }; - - $ax.public.fn.moveBy = function (x, y, options) { - var elementIds = this.getElementIds(); - - if(x == 0 && y == 0) { - for(var i = 0; i < elementIds.length; i++) { - var elementId = elementIds[i]; - $ax.move.nopMove(elementId, options); - - //$ax.event.raiseSyntheticEvent(elementId, "onMove"); - $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.move); - - //if($axure.fn.IsLayer($obj(elementId).type)) { - // var childrenIds = $ax.public.fn.getLayerChildrenDeep(elementId, true); - // for(var j = 0; j < childrenIds.length; j++) $ax.event.raiseSyntheticEvent(childrenIds[j], 'onMove'); - //} - } - return this; - } - - for(var index = 0; index < elementIds.length; index++) { - _move(elementIds[index], x, y, options, false); - } - return this; - }; - - $ax.public.fn.circularMoveAndRotate = function(degreeChange, options, centerPointLeft, centerPointTop, doRotation, moveDelta, resizeOffset, rotatableMove, moveComplete) { - if(!rotatableMove) rotatableMove = { x: 0, y: 0 }; - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - - var onComplete = function () { - $ax.dynamicPanelManager.fitParentPanel(elementId); - if (moveComplete) moveComplete(); - } - - $ax.move.circularMove(elementId, degreeChange, { x: centerPointLeft, y: centerPointTop }, moveDelta, rotatableMove, resizeOffset, options, true, onComplete, doRotation); - if(doRotation) $ax.move.rotate(elementId, degreeChange, options.easing, options.duration, false, true, function () { $ax.dynamicPanelManager.fitParentPanel(elementId); }); - else $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.rotate); - } - }; - - $ax.public.fn.rotate = function (degree, easing, duration, to, axShouldFire) { - var elementIds = this.getElementIds(); - // this function will no longer handle compound vectors. - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - degree = parseFloat(degree); - $ax.move.rotate(elementId, degree, easing, duration, to, axShouldFire, function () { $ax.dynamicPanelManager.fitParentPanel(elementId); }); - } - }; - - $ax.public.fn.resize = function(newLocationAndSizeCss, resizeInfo, axShouldFire, moves, onCompletedFunc) { - var elementIds = this.getElementIds(); - if(!elementIds) return; - - var completeAndFire = function(moved, id) { - if(axShouldFire) { - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.resize); - if(moves) $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.move); - } - - if(onCompletedFunc) onCompletedFunc(); - }; - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - - var obj = $obj(elementId); - if(!$ax.public.fn.IsResizable(obj.type)) { - //$ax.dynamicPanelManager.fitParentPanel(elementId); - completeAndFire(moves, elementId); - continue; - } - - var oldSize = $ax('#' + elementId).size(); - var oldWidth = oldSize.width; - var oldHeight = oldSize.height; - var query = $jobj(elementId); - - var isDynamicPanel = $ax.public.fn.IsDynamicPanel(obj.type); - if(isDynamicPanel) { - // No longer fitToContent, calculate additional styling that needs to be done. - $ax.dynamicPanelManager.setFitToContentCss(elementId, false, oldWidth, oldHeight); - - if (query.css('position') == 'fixed' && ((obj.fixedHorizontal && obj.fixedHorizontal == 'center') || (obj.fixedVertical && obj.fixedVertical == 'middle'))) { - moves = true; - var loc = $ax.dynamicPanelManager.getFixedPosition(elementId, oldWidth, oldHeight, newLocationAndSizeCss.width, newLocationAndSizeCss.height); - if(loc) { - if (loc[0] != 0 && !$ax.dynamicPanelManager.isPercentWidthPanel(obj)) newLocationAndSizeCss['margin-left'] = '+=' + (Number(newLocationAndSizeCss['margin-left'].substr(2)) + loc[0]); - if (loc[1] != 0) newLocationAndSizeCss['margin-top'] = '+=' + (Number(newLocationAndSizeCss['margin-top'].substr(2)) + loc[1]); - } - } - - var onComplete = function() { - $ax.flyoutManager.updateFlyout(elementId); - $ax.dynamicPanelManager.fitParentPanel(elementId); - $ax.dynamicPanelManager.updatePanelPercentWidth(elementId); - $ax.dynamicPanelManager.updatePanelContentPercentWidth(elementId); - - completeAndFire(moves, elementId); - $ax.event.raiseSyntheticEvent(elementId, 'onResize'); - }; - - } else { - ////if contains text - //var textChildren = query.children('div.text'); - //if(textChildren && textChildren.length != 0) { - // var textDivId = textChildren.attr('id'); - // var padding = $ax.style.getPadding(textDivId); - // var leftPadding = padding.paddingLeft; - // var rightPadding = padding.paddingRight; - // //var textObj = $ax('#' + textDivId); - // //var leftPadding = textObj.left(true); - // //var rightPadding = oldWidth - leftPadding - textObj.width(); - - // //greater or equal to 1px - // var newTextWidth = Math.max(newLocationAndSizeCss.width - leftPadding - rightPadding, 1); - // var textChildCss = { width: newTextWidth }; - - // var textStepFunction = function() { - // //change the width of the text div may effect the height - // //var currentTextHeight = Number($(textChildren.children('p')[0]).css('height').replace('px', '')); - // //textChildren.css('height', currentTextHeight); - // //var display = $ax.public.fn.displayHackStart(document.getElementById(textDivId)); - - // var trap = _displayWidget(textDivId); - // $ax.style.setTextAlignment([textDivId]); - // trap(); - - // //$ax.public.fn.displayHackEnd(display); - // }; - //} - - //get all the other children that matters - onComplete = function() { - $ax.dynamicPanelManager.fitParentPanel(elementId); - completeAndFire(moves, elementId); - - $ax.annotation.adjustIconLocation(elementId); - $ax.event.raiseSyntheticEvent(elementId, 'onResize'); - }; - } - - var children = query.children().not('div.text'); - while(children && children.length && $(children[0]).attr('id').indexOf('container') != -1) { - children = children.children().not('div.text'); - } - - if(children && children.length !== 0) { - var childAnimationArray = []; - var isConnector = $ax.public.fn.IsConnector(obj.type); - children.each(function (i, child) { - var childCss = { - width: newLocationAndSizeCss.width, - height: newLocationAndSizeCss.height - }; - - //$ax.size() use outerWidth/Height(false), which include padding and borders(no margins) - var childSizingObj = $ax('#' + child.id).size(); - var differentSizedImage = childSizingObj.width - oldWidth != 0 || childSizingObj.height - oldHeight != 0; - if ((differentSizedImage || isConnector) && child.tagName == 'IMG') { - //oldwidth is zero for connectors - var widthOffset = oldWidth ? (childSizingObj.width - oldWidth) * newLocationAndSizeCss.width / oldWidth : childSizingObj.width; - var heightOffset = oldHeight ? (childSizingObj.height - oldHeight) * newLocationAndSizeCss.height / oldHeight : childSizingObj.height; - - childCss.width += widthOffset; - childCss.height += heightOffset; - } - //there are elements like inputs, come with a padding and border, so need to use outerwidth for starting point, due to jquery 1.7 css() on width/height bugs - if($(child).css('position') === 'absolute') { - if(child.offsetLeft) { - childSizingObj.left = child.offsetLeft; - childCss.left = oldWidth ? child.offsetLeft * newLocationAndSizeCss.width / oldWidth : child.offsetLeft; //- transformedShift.x; - } - if(child.offsetTop) { - childSizingObj.top = child.offsetTop; - childCss.top = oldHeight ? child.offsetTop * newLocationAndSizeCss.height / oldHeight : child.offsetTop; //- transformedShift.y; - } - } - childAnimationArray.push({ obj: child, sizingObj: childSizingObj, sizingCss: childCss }); - }); - } - - if (newLocationAndSizeCss.left || newLocationAndSizeCss.top) { - //var movedLeft = newLocationAndSizeCss.left; - //var movedTop = newLocationAndSizeCss.top; - //$ax.visibility.setMovedLocation(elementId, movedLeft, movedTop); - var movedLeft = newLocationAndSizeCss.deltaX; - var movedTop = newLocationAndSizeCss.deltaY; - $ax.visibility.moveMovedLocation(elementId, movedLeft, movedTop); - } - if (newLocationAndSizeCss.width || newLocationAndSizeCss.height) { - var resizedWidth = newLocationAndSizeCss.width; - var resizedHeight = newLocationAndSizeCss.height; - $ax.visibility.setResizedSize(elementId, resizedWidth, resizedHeight); - } - - if (!resizeInfo.easing || resizeInfo.easing == 'none') { - if (childAnimationArray) { - $(childAnimationArray).each(function (i, animationObj) { - if(animationObj.resizeMatrixFunction) { - $(animationObj.obj).css($ax.public.fn.setTransformHowever(animationObj.resizeMatrixFunction(animationObj.width, animationObj.height))); - } else { - //var sizingCss = animationObj.sizingCss; - //if (sizingCss.left || sizingCss.top) { - // var movedLeft = sizingCss.left; - // var movedTop = sizingCss.top; - // $ax.visibility.setMovedLocation(animationObj.obj.id, movedLeft, movedTop); - //} - //if (sizingCss.width || sizingCss.height) { - // var resizedWidth = sizingCss.width; - // var resizedHeight = sizingCss.height; - // $ax.visibility.setResizedSize(animationObj.obj.id, resizedWidth, resizedHeight); - //} - - $(animationObj.obj).animate(animationObj.sizingCss, { queue: false, duration: 0 }); - } - }); - } - //if(childCss) children.animate(childCss, 0); - //if(sketchyImage && sketchyImageCss) $(sketchyImage).animate(sketchyImageCss, 0); - //if(textChildCss) { - // textChildren.animate(textChildCss, { - // duration: 0, - // step: textStepFunction - // }); - //} - query.animate(newLocationAndSizeCss, { queue: false, duration: 0, complete: onComplete }); - } else { - if(childAnimationArray) { - $(childAnimationArray).each(function (i, animationObj) { - if(animationObj.resizeMatrixFunction) { - $(animationObj.sizingObj).animate(animationObj.sizingCss, { - queue: false, - duration: resizeInfo.duration, - easing: resizeInfo.easing, - step: function (now) { - var widthRatio = (animationObj.width - 1.0) * now + 1.0; - var heightRatio = (animationObj.height - 1.0) * now + 1.0; - $(animationObj.obj).css($ax.public.fn.setTransformHowever(animationObj.resizeMatrixFunction(widthRatio, heightRatio))); - } - }); - } else { - $(animationObj.sizingObj).animate(animationObj.sizingCss, { - queue: false, - duration: resizeInfo.duration, - easing: resizeInfo.easing, - step: function (now, tween) { - $(animationObj.obj).css(tween.prop, now); - } - }); - } - }); - } - - //if(textChildCss) { - // textChildren.animate(textChildCss, { - // queue: false, - // duration: resizeInfo.duration, - // easing: resizeInfo.easing, - // step: textStepFunction - // }); - //} - - if(isDynamicPanel) { - query.animate(newLocationAndSizeCss, { queue: false, duration: resizeInfo.duration, easing: resizeInfo.easing, complete: onComplete }); - } else { - var locObj = { - left: $ax.public.fn.GetFieldFromStyle(query, 'left'), top: $ax.public.fn.GetFieldFromStyle(query, 'top'), - width: $ax.public.fn.GetFieldFromStyle(query, 'width'), height: $ax.public.fn.GetFieldFromStyle(query, 'height'), - }; - $(locObj).animate(newLocationAndSizeCss, { - queue: false, - duration: resizeInfo.duration, - easing: resizeInfo.easing, - step: function (now, tween) { - query.css(tween.prop, now); - }, - complete: onComplete - }); - } - } - } - }; - - $ax.public.fn.bringToFront = function() { - var elementIds = this.getElementIds(); - for(var index = 0; index < elementIds.length; index++) { $ax.legacy.BringToFront(elementIds[index]); } - return this; - }; - - $ax.public.fn.sendToBack = function() { - var elementIds = this.getElementIds(); - for(var index = 0; index < elementIds.length; index++) { $ax.legacy.SendToBack(elementIds[index]); } - return this; - }; - - $ax.public.fn.text = function() { - if(arguments[0] == undefined) { - var firstId = this.getElementIds()[0]; - - if(!firstId) { return undefined; } - - return getWidgetText(firstId); - } else { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var currentItem = elementIds[index]; - - var widgetType = $ax.getTypeFromElementId(currentItem); - - if($ax.public.fn.IsTextBox(widgetType) || $ax.public.fn.IsTextArea(widgetType)) { //For non rtf - SetWidgetFormText(currentItem, arguments[0]); - } else { - var idRtf = '#' + currentItem; - if($(idRtf).length == 0) idRtf = '#u' + (Number(currentItem.substring(1)) + 1); - - if($(idRtf).length != 0) { - //If the richtext div already has some text in it, - //preserve only the first style and get rid of the rest - //If no pre-existing p-span tags, don't do anything - if($(idRtf).find('p').find('span').length > 0) { - $(idRtf).find('p:not(:first)').remove(); - $(idRtf).find('p').find('span:not(:first)').remove(); - - //Replace new-lines with NEWLINE token, then html encode the string, - //finally replace NEWLINE token with linebreak - var textWithLineBreaks = arguments[0].replace(/\n/g, '--NEWLINE--'); - var textHtml = $('<div/>').text(textWithLineBreaks).html(); - $(idRtf).find('span').html(textHtml.replace(/--NEWLINE--/g, '<br>')); - } - } - } - } - - return this; - } - }; - - var getWidgetText = function(id) { - var idQuery = $jobj(id); - var inputQuery = $jobj($ax.INPUT(id)); - if(inputQuery.length) idQuery = inputQuery; - - if (idQuery.is('input') && ($ax.public.fn.IsCheckBox(idQuery.attr('type')) || idQuery.attr('type') == 'radio')) { - idQuery = idQuery.parent().find('label').find('div'); - } - - if(idQuery.is('div')) { - var $rtfObj = idQuery.hasClass('text') ? idQuery : idQuery.find('.text'); - if($rtfObj.length == 0) return ''; - - var textOut = ''; - $rtfObj.children('p,ul,ol').each(function(index) { - if(index != 0) textOut += '\n'; - - //var htmlContent = $(this).html(); - //if(isSoloBr(htmlContent)) return; // It has a solo br, then it was just put in for a newline, and paragraph already added the new line. - if (isSoloBr($(this).children())) return; - - var htmlContent = $(this).html(); - //Replace line breaks (set in SetWidgetRichText) with newlines and nbsp's with regular spaces. - htmlContent = htmlContent.replace(/<br[^>]*>/ig, '\n').replace(/ /ig, ' '); - textOut += $(htmlContent).text(); - //textOut += htmlContent.replace(/<[^>]*>/g, ''); - }); - - return textOut; - } else { - var val = idQuery.val(); - return val == undefined ? '' : val; - } - }; - - var isSoloBr = function($html) { - //html = $(html); - // Html needs one and only one span - var spanChildren = $html.length == 1 && $html.is('span') ? $html.children() : false; - // Span children needs exactly one br and no text in the span - return spanChildren && spanChildren.length == 1 && spanChildren.is('br') && spanChildren.text().trim() == ''; - }; - - $ax.public.fn.setRichTextHtml = function() { - if(arguments[0] == undefined) { - //No getter function, so just return undefined - return undefined; - } else { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var currentItem = elementIds[index]; - - var widgetType = $ax.getTypeFromElementId(currentItem); - if ($ax.public.fn.IsTextBox(widgetType) || $ax.public.fn.IsTextArea(widgetType)) { //Do nothing for non rtf - continue; - } else { - //TODO -- [mas] fix this! - var idRtf = '#' + currentItem; - if($(idRtf).length == 0) idRtf = '#u' + (parseInt(currentItem.substring(1)) + 1); - if($(idRtf).length != 0) SetWidgetRichText(idRtf, arguments[0]); - } - } - - return this; - } - }; - - $ax.public.fn.value = function() { - if(arguments[0] == undefined) { - var firstId = this.getElementIds()[0]; - - if(!firstId) { - return undefined; - } - - var widgetType = $ax.getTypeFromElementId(firstId); - - if ($ax.public.fn.IsComboBox(widgetType) || $ax.public.fn.IsListBox(widgetType)) { //for select lists and drop lists - return $('#' + firstId + ' :selected').text(); - } else if ($ax.public.fn.IsCheckBox(widgetType) || $ax.public.fn.IsRadioButton(widgetType)) { //for radio/checkboxes - return $('#' + firstId + '_input').is(':selected'); - } else if ($ax.public.fn.IsTextBox(widgetType)) { //for text box - return $('#' + firstId + '_input').val(); - } else { //for text based form elements - return this.jQuery().first().val(); - } - } else { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var widgetType = $ax.getTypeFromElementId(elementIds[index]); - - var elementIdQuery = $('#' + elementIds[index]); - - if ($ax.public.fn.IsCheckBox(widgetType) || $ax.public.fn.IsRadioButton(widgetType)) { //for radio/checkboxes - if(arguments[0] == true) { - elementIdQuery.prop('selected', true); - } else if(arguments[0] == false) { - elementIdQuery.prop('selected', false); - } - } else { //For select lists, drop lists, text based form elements - elementIdQuery.val(arguments[0]); - } - } - - return this; - } - }; - - $ax.public.fn.checked = function() { - if(arguments[0] == undefined) { - return this.selected(); - } else { - this.selected(arguments[0]); - return this; - } - }; - - //var _getRelativeLeft = function (id, parent) { - // var currentNode = window.document.getElementById(id).offsetParent; - // var left = $ax('#' + id).left(true); - // while (currentNode != null && currentNode.tagName != "BODY" && currentNode != parent) { - // left += currentNode.offsetLeft; - // currentNode = currentNode.offsetParent; - // } - // return left; - //}; - - //var _getRelativeTop = function(id, parent) { - // var currentNode = window.document.getElementById(id).offsetParent; - // var top = $ax('#' + id).top(true); - // while(currentNode != null && currentNode.tagName != "BODY" && currentNode != parent) { - // top += currentNode.offsetTop; - // currentNode = currentNode.offsetParent; - // } - // return top; - //}; - - var _scrollHelper = function(id, scrollX, scrollY, easing, duration) { - var target = window.document.getElementById(id); - var scrollable = $ax.legacy.GetScrollable(target); - var $scrollable = $(scrollable); - - var viewportLocation; - if ($scrollable.is('body')) viewportLocation = $ax('#' + id).viewportLocation(); - else viewportLocation = $ax('#' + id).pageBoundingRect(true, $scrollable.attr('id')).location; - - var targetLeft = viewportLocation.left; - var targetTop = viewportLocation.top; - //var targetLeft = _getRelativeLeft(id, scrollable); - //var targetTop = _getRelativeTop(id, scrollable); - if(!scrollX) targetLeft = scrollable.scrollLeft; - if(!scrollY) targetTop = scrollable.scrollTop; - - if($scrollable.is('body')) { - $scrollable = $('html,body'); - } - if(easing == 'none') { - if(scrollY) $scrollable.scrollTop(targetTop); - if(scrollX) $scrollable.scrollLeft(targetLeft); - } else { - if(!scrollX) { - $scrollable.animate({ scrollTop: targetTop }, duration, easing); - } else if(!scrollY) { - $scrollable.animate({ scrollLeft: targetLeft }, duration, easing); - } else { - $scrollable.animate({ scrollTop: targetTop, scrollLeft: targetLeft }, duration, easing); - } - } - }; - - $ax.public.fn.scroll = function(scrollOption) { - var easing = 'none'; - var duration = 500; - - if(scrollOption && scrollOption.easing) { - easing = scrollOption.easing; - - if(scrollOption.duration) { - duration = scrollOption.duration; - } - } - - var scrollX = true; - var scrollY = true; - - // TODO: check this without vertical option -- might scroll outside of device frame - if(scrollOption.direction == 'vertical') { - scrollX = false; - } else if(scrollOption.direction == 'horizontal') { - scrollY = false; - } - - var elementIds = this.getElementIds(); - for(var index = 0; index < elementIds.length; index++) { - // if($ax.getTypeFromElementId(elementIds[index]) == IMAGE_MAP_REGION_TYPE) { - _scrollHelper(elementIds[index], scrollX, scrollY, easing, duration); - // } - } - - return this; - }; - - $ax.public.fn.enabled = function() { - if(arguments[0] == undefined) { - var firstId = this.getElementIds()[0]; - if(!firstId) return undefined; - - var widgetType = $ax.getTypeFromElementId(firstId); - if ($ax.public.fn.IsImageBox(widgetType) || $ax.public.fn.IsVector(widgetType) - || $ax.public.fn.IsLayer(widgetType)) return !$ax.style.IsWidgetDisabled(firstId); - else return this.jQuery().children(':disabled').length <= 0; - } else { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - var widgetType = $ax.getTypeFromElementId(elementId); - - var enabled = arguments[0]; - if ($ax.public.fn.IsImageBox(widgetType) || $ax.public.fn.IsVector(widgetType) - || $ax.public.fn.IsTextBox(widgetType) || $ax.public.fn.IsTextArea(widgetType) - || $ax.public.fn.IsComboBox(widgetType) || $ax.public.fn.IsListBox(widgetType) - || $ax.public.fn.IsCheckBox(widgetType) || $ax.public.fn.IsRadioButton(widgetType) - ) $ax.style.SetWidgetEnabled(elementId, enabled); - - if ($ax.public.fn.IsDynamicPanel(widgetType) || $ax.public.fn.IsLayer(widgetType)) { - $ax.style.SetWidgetEnabled(elementId, enabled); - var children = this.getChildren(false, true)[index].children; - for(var i = 0; i < children.length; i++) { - $axure('#' + children[i]).enabled(enabled); - } - } - var obj = $obj(elementId); - var images = obj.images; - if(PLAIN_TEXT_TYPES.indexOf(widgetType) != -1 && images) { - var img = $jobj($ax.repeater.applySuffixToElementId(elementId, '_image_sketch')); - var key = (enabled ? 'normal~' : 'disabled~') + ($ax.adaptive.currentViewId || ''); - img.attr('src', images[key]); - - } - var jobj = $jobj(elementId); - var input = $jobj($ax.INPUT(elementId)); - if(input.length) jobj = input; - - //if (OS_MAC && WEBKIT && $ax.public.fn.IsComboBox(widgetType)) jobj.css('color', enabled ? '' : 'grayText'); - if($ax.public.fn.IsCheckBox(widgetType) || $ax.public.fn.IsRadioButton(widgetType)) return this; - if(enabled) jobj.prop('disabled', false); - else jobj.prop('disabled', true); - } - - return this; - } - }; - - $ax.public.fn.visible = function() { - var ids = this.getElementIds(); - for(var index = 0; index < ids.length; index++) $ax.visibility.SetIdVisible(ids[index], arguments[0]); - return this; - }; - - $ax.public.fn.selected = function() { - if(arguments[0] == undefined) { - var firstId = this.getElementIds()[0]; - if(!firstId) return undefined; - - var widgetType = $ax.getTypeFromElementId(firstId); - if ($ax.public.fn.IsTreeNodeObject(widgetType)) { - var treeNodeButtonShapeId = ''; - var allElementIds = $ax.getAllElementIds(); - for(var i = 0; i < allElementIds.length; i++) { - var elementId = allElementIds[i]; - var currObj = $ax.getObjectFromElementId(elementId); - - if ($ax.public.fn.IsVector(currObj.type) && currObj.parent && currObj.parent.scriptIds && currObj.parent.scriptIds[0] == firstId) { - treeNodeButtonShapeId = elementId; - break; - } - } - - if(treeNodeButtonShapeId == '') return undefined; - return $ax.style.IsWidgetSelected(treeNodeButtonShapeId); - } else if ($ax.public.fn.IsImageBox(widgetType) || $ax.public.fn.IsVector(widgetType) || $ax.public.fn.IsTableCell(widgetType) || $ax.public.fn.IsDynamicPanel(widgetType) || $ax.public.fn.IsLayer(widgetType) - || $ax.public.fn.IsTextArea(widgetType) || $ax.public.fn.IsTextBox(widgetType) || $ax.public.fn.IsListBox(widgetType) || $ax.public.fn.IsComboBox(widgetType)) { - return $ax.style.IsWidgetSelected(firstId); - } else if ($ax.public.fn.IsCheckBox(widgetType) || $ax.public.fn.IsRadioButton(widgetType)) { - return $jobj($ax.INPUT(firstId)).prop('checked'); - } - return this; - } - var elementIds = this.getElementIds(); - var func = typeof (arguments[0]) === 'function' ? arguments[0] : null; - var enabled = arguments[0]; // If this is a function it will be overridden with the return value; - - for(var index = 0; index < elementIds.length; index++) { - var elementId = elementIds[index]; - if(func) { - enabled = func($axure('#' + elementId)); - } - - var widgetType = $ax.getTypeFromElementId(elementId); - - if ($ax.public.fn.IsTreeNodeObject(widgetType)) { //for tree node - var treeRootId = $('#' + elementIds[index]).parents('.treeroot').attr('id'); - - var treeNodeButtonShapeId = ''; - var childElementIds = $jobj(elementId).children(); - for(var i = 0; i < childElementIds.length; i++) { - var elementId = childElementIds[i].id; - var currObj = $ax.getObjectFromElementId(elementId); - - if (currObj && currObj.type == $ax.constants.VECTOR_SHAPE_TYPE && currObj.parent && - currObj.parent.scriptIds && currObj.parent.scriptIds[0] == elementIds[index]) { - treeNodeButtonShapeId = elementId; - break; - } - } - - if(treeNodeButtonShapeId == '') continue; - - $ax.tree.SelectTreeNode(elementId, enabled); - } else if ($ax.public.fn.IsImageBox(widgetType) || $ax.public.fn.IsVector(widgetType) || $ax.public.fn.IsTableCell(widgetType) || $ax.public.fn.IsDynamicPanel(widgetType) || $ax.public.fn.IsLayer(widgetType) - || $ax.public.fn.IsTextArea(widgetType) || $ax.public.fn.IsTextBox(widgetType) || $ax.public.fn.IsListBox(widgetType) || $ax.public.fn.IsComboBox(widgetType)) { - $ax.style.SetWidgetSelected(elementIds[index], enabled); - } else if ($ax.public.fn.IsCheckBox(widgetType) || $ax.public.fn.IsRadioButton(widgetType)) { - var query = $jobj($ax.INPUT(elementId)); - var curr = query.prop('checked'); - //NOTE: won't fire onselect nore onunselect event if states didn't changes - if(curr != enabled) { - query.prop('checked', enabled); - $ax.style.SetWidgetSelected(elementIds[index], enabled, true); - } - } - } - return this; - }; - - $ax.public.fn.focus = function() { - var firstId = this.getElementIds()[0]; - var focusableId = $ax.event.getFocusableWidgetOrChildId(firstId); - // This will scroll but not focus - $('#' + focusableId).triggerHandler("focus"); - // This will focus but does not call our custom scroll so will not animate scroll - $('#' + focusableId).focus(); - - return this; - }; - - $ax.public.fn.expanded = function() { - if(arguments[0] == undefined) { - var firstId = this.getElementIds()[0]; - return firstId && !$ax.public.fn.IsTreeNodeObject($ax.getTypeFromElementId(firstId)) && $ax.visibility.IsIdVisible(firstId + '_children'); - } else { - var elementIds = this.getElementIds(); - - for(var index = 0; index < elementIds.length; index++) { - if ($ax.public.fn.IsTreeNodeObject($ax.getTypeFromElementId(elementIds[index]))) { - var treeNodeId = elementIds[index]; - var childContainerId = treeNodeId + '_children'; - - var scriptId = $ax.repeater.getScriptIdFromElementId(treeNodeId); - var itemId = $ax.repeater.getItemIdFromElementId(treeNodeId); - var plusMinusId = 'u' + (parseInt(scriptId.substring(1)) + 1); - if(itemId) plusMinusId = $ax.repeater.createElementId(plusMinusId, itemId); - if($('#' + childContainerId).length == 0 || !$jobj(plusMinusId).children().first().is('img')) - plusMinusId = ''; - - if(arguments[0] == true) { - $ax.tree.ExpandNode(treeNodeId, childContainerId, plusMinusId); - } else if(arguments[0] == false) { - $ax.tree.CollapseNode(treeNodeId, childContainerId, plusMinusId); - } - } - } - - return this; - } - }; - - var _populateBoundingRect = function (boundingRect) { - boundingRect.right = boundingRect.left + boundingRect.width; - boundingRect.bottom = boundingRect.top + boundingRect.height; - - boundingRect.x = boundingRect.left; - boundingRect.y = boundingRect.top; - - boundingRect.location = { - x: boundingRect.left, - y: boundingRect.top, - left: boundingRect.left, - top: boundingRect.top - }; - - boundingRect.size = { - width: boundingRect.width, - height: boundingRect.height - }; - - boundingRect.centerPoint = { - x: boundingRect.width / 2 + boundingRect.left, - y: boundingRect.height / 2 + boundingRect.top - }; - return boundingRect; - } - - //boundingrect relative to its offset parent - //var _getBoundingRectForSingleWidget = function (elementId) { - // var element = document.getElementById(elementId); - // var tempBoundingRect, position; - - // var state = $ax.style.generateState(elementId); - // var style = $ax.style.computeFullStyle(elementId, state, $ax.adaptive.currentViewId); - // position = { left: style.location.x, top: style.location.y }; - // tempBoundingRect = { left: style.location.x, top: style.location.y, width: style.size.width, height: style.size.height }; - - // if ($ax.public.fn.isCompoundVectorHtml(element)) { - // tempBoundingRect.width = Number(element.getAttribute('data-width')); - // tempBoundingRect.height = Number(element.getAttribute('data-height')); - // } else { - // var boundingElement = element; - // if ($ax.dynamicPanelManager.isIdFitToContent(elementId)) { - // var stateId = $ax.visibility.GetPanelState(elementId); - // if (stateId != '') boundingElement = document.getElementById(stateId); - // tempBoundingRect = boundingElement.getBoundingClientRect(); - // } - - // //From getLoc - // //var fixed = _fixedOffset(id, vert); - // //if (fixed.valid) loc = !vert && fixed.fullWidth ? 0 : fixed.offset; - - // var jElement = $(element); - // if (jElement.css('position') == 'fixed') { - // position = jElement.position(); - // position.left += Number(jElement.css('margin-left').replace("px", "")); - // position.top += Number(jElement.css('margin-top').replace("px", "")); - // } - // } - - // var boundingRect = { - // left: position.left, - // top: position.top, - // width: tempBoundingRect.width, - // height: tempBoundingRect.height - // }; - - // return _populateBoundingRect(boundingRect); - //}; - - //var _getBoundingRectForMultipleWidgets = function (widgetsIdArray) { - // if (!widgetsIdArray || widgetsIdArray.constructor !== Array) return undefined; - // if (widgetsIdArray.length == 0) return { left: 0, top: 0, centerPoint: { x: 0, y: 0 }, width: 0, height: 0 }; - // var widgetRect = _getBoundingRectForSingleWidget(widgetsIdArray[0]); - // var boundingRect = { left: widgetRect.left, right: widgetRect.right, top: widgetRect.top, bottom: widgetRect.bottom }; - - // for (var index = 1; index < widgetsIdArray.length; index++) { - // widgetRect = _getBoundingRectForSingleWidget(widgetsIdArray[index]); - // boundingRect.left = Math.min(boundingRect.left, widgetRect.left); - // boundingRect.top = Math.min(boundingRect.top, widgetRect.top); - // boundingRect.right = Math.max(boundingRect.right, widgetRect.right); - // boundingRect.bottom = Math.max(boundingRect.bottom, widgetRect.bottom); - // } - - // boundingRect.centerPoint = { x: (boundingRect.right + boundingRect.left) / 2.0, y: (boundingRect.bottom + boundingRect.top) / 2.0 }; - // boundingRect.width = boundingRect.right - boundingRect.left; - // boundingRect.height = boundingRect.bottom - boundingRect.top; - // return _populateBoundingRect(boundingRect); - //}; - - //var _getLayerChildrenDeep = $ax.public.fn.getLayerChildrenDeep = function (layerId, includeLayers, includeHidden) { - // var deep = []; - // var children = $ax('#' + layerId).getChildren()[0].children; - // for (var index = 0; index < children.length; index++) { - // var childId = children[index]; - // if (!includeHidden && !$ax.visibility.IsIdVisible(childId)) continue; - // if ($ax.public.fn.IsLayer($obj(childId).type)) { - // if (includeLayers) deep.push(childId); - // var recursiveChildren = _getLayerChildrenDeep(childId, includeLayers, includeHidden); - // for (var j = 0; j < recursiveChildren.length; j++) deep.push(recursiveChildren[j]); - // } else deep.push(childId); - // } - // return deep; - //}; - - var _boundingRectForIds = function(childIds) { - // Default size - var childrenBoundingRect = { left: childIds.length > 0 ? 9999999 : 0, top: childIds.length > 0 ? 9999999 : 0, right: 0, bottom: 0 }; - for (var i = 0; i < childIds.length; i++) { - var childId = childIds[i]; - var childObj = $obj(childId); - - if (!childObj) continue; - - // Ignore fixed and hidden - if ($ax.visibility.limboIds[childId] || - !$ax.visibility.IsIdVisible(childId) || - $ax.public.fn.IsDynamicPanel(childObj.type) && childObj.fixedHorizontal) continue; - - var boundingRect = $ax('#' + childId).offsetBoundingRect(); - - // Ignore empty groups - if ($ax.public.fn.IsLayer(childObj.type) && boundingRect.width == 0 && boundingRect.height == 0) continue; - - childrenBoundingRect.left = Math.min(childrenBoundingRect.left, boundingRect.left); - childrenBoundingRect.top = Math.min(childrenBoundingRect.top, boundingRect.top); - childrenBoundingRect.right = Math.max(childrenBoundingRect.right, boundingRect.right); - childrenBoundingRect.bottom = Math.max(childrenBoundingRect.bottom, boundingRect.bottom); - } - childrenBoundingRect.width = childrenBoundingRect.right - childrenBoundingRect.left; - childrenBoundingRect.height = childrenBoundingRect.bottom - childrenBoundingRect.top; - - return _populateBoundingRect(childrenBoundingRect); - } - - $ax.public.fn.getPageSize = function() { - var containerQuery = $('#base'); - var children = containerQuery.children(); - var childIds = []; - for (var i = 0; i < children.length; i++) { - var child = $(children[i]); - var childId = child.attr('id'); - childIds.push(childId); - } - - return _boundingRectForIds(childIds); - } - - $ax.public.fn.childrenBoundingRect = function () { - var childIds = this.getChildren()[0].children; - return _boundingRectForIds(childIds); - }; - - var _fixedLocation = function (elementId, size) { - var axObj = $obj(elementId); - if (!axObj || !axObj.fixedVertical) return { valid: false }; - - var win = ((SAFARI && IOS) || SHARE_APP) ? $('#ios-safari-html') : $(window); - var windowWidth = win.width(); - var windowHeight = win.height(); - //getting the scroll forces layout. consider caching these values. - var windowScrollLeft = win.scrollLeft(); - var windowScrollTop = win.scrollTop(); - - var newLeft = 0; - var newTop = 0; - var width = size.width; - var height = size.height; - - var horz = axObj.fixedHorizontal; - if(horz == 'left') { - newLeft = windowScrollLeft + (axObj.percentWidth ? 0 : $ax.getNumFromPx($jobj(elementId).css('left'))); - } else if(horz == 'center') { - newLeft = windowScrollLeft + ((windowWidth - width) / 2) + axObj.fixedMarginHorizontal; - } else if(horz == 'right') { - newLeft = windowScrollLeft + windowWidth - width - axObj.fixedMarginHorizontal; - } - - var vert = axObj.fixedVertical; - if(vert == 'top') { - newTop = windowScrollTop + $ax.getNumFromPx($jobj(elementId).css('top')); - } else if(vert == 'middle') { - newTop = windowScrollTop + ((windowHeight - height) / 2) + axObj.fixedMarginVertical; - } else if(vert == 'bottom') { - newTop = windowScrollTop + windowHeight - height - axObj.fixedMarginVertical; - } - - //probably need to make this relative to the page for hit testing - return { valid: true, top: newTop, left: axObj.isPercentWidthPanel ? 0 : newLeft }; - }; - - //relative to the parent - $ax.public.fn.offsetBoundingRect = function (ignoreRotation) { - var elementId = this.getElementIds()[0]; - if (!elementId) return undefined; - - //element is null if RDO - //data- values are for layers (legacy compound) - var element = document.getElementById(elementId); - var position, size, rotation; - - var trap; - var state; - var style; - var movedLoc = $ax.visibility.getMovedLocation(elementId); - var resizedSize = $ax.visibility.getResizedSize(elementId); - - if (movedLoc) { - position = movedLoc; - } else if(element && element.getAttribute('data-left')) { - position = { - left: Number(element.getAttribute('data-left')), - top: Number(element.getAttribute('data-top')) - }; - } else if($obj(elementId)) { - state = $ax.style.generateState(elementId); - style = $ax.style.computeFullStyle(elementId, state, $ax.adaptive.currentViewId); - position = { left: style.location.x, top: style.location.y }; - - var oShadow = style.outerShadow; - - if (oShadow.on) { - if (oShadow.offsetX < 0) { - position.left += oShadow.offsetX; - position.left -= oShadow.blurRadius; - } - if (oShadow.offsetY < 0) { - position.top += oShadow.offsetY; - position.top -= oShadow.blurRadius; - } - } - - var parents = this.getParents(true, '*')[0]; - //if(parents.length > 0) { - // var parentId = parents[0]; - // var type = $ax.getTypeFromElementId(parentId); - // if ($axure.fn.IsReferenceDiagramObject(type)) { - // var rdoLoc = $ax('#' + parentId).offsetLocation(); - // position.left += rdoLoc.x; - // position.top += rdoLoc.y; - // } - //} - for(var i = 0; i < parents.length; i++) { - var parentId = parents[i]; - var type = $ax.getTypeFromElementId(parentId); - if ($axure.fn.IsReferenceDiagramObject(type)) { - var rdoLoc = $ax('#' + parentId).offsetLocation(); - position.left += rdoLoc.x; - position.top += rdoLoc.y; - break; - } else if (!$axure.fn.IsLayer(type)) break; - } - } else { - if (!trap) trap = _displayWidget($ax.repeater.removeSuffixFromElementId(elementId)); - var jObjPosition = $(element).position(); - position = { left: jObjPosition.left, top: jObjPosition.top }; - } - - if (resizedSize) { - size = resizedSize; - } else if (element && element.getAttribute('data-width')) { - size = { - width: Number(element.getAttribute('data-width')), - height: Number(element.getAttribute('data-height')) - }; - } else if($obj(elementId)) { - state = state || $ax.style.generateState(elementId); - style = style || $ax.style.computeFullStyle(elementId, state, $ax.adaptive.currentViewId); - size = { width: style.size.width, height: style.size.height }; - - var oShadow = style.outerShadow; - - if (oShadow.on) { - if (oShadow.offsetX < 0) size.width -= oShadow.offsetX; - else size.width += oShadow.offsetX; - if (oShadow.offsetY < 0) size.height -= oShadow.offsetY; - else size.height += oShadow.offsetY; - - size.width += oShadow.blurRadius; - size.height += oShadow.blurRadius; - } - } else { - if(!trap) trap = _displayWidget($ax.repeater.removeSuffixFromElementId(elementId)); - var jObj = $(element); - size = { width: jObj.outerWidth(), height: jObj.outerHeight() }; - } - - var fixed = _fixedLocation(elementId, size); - if(fixed.valid) { - position.left = fixed.left; - position.top = fixed.top; - } - - var boundingRect = { - left: position.left, - top: position.top, - width: size.width, - height: size.height, - isFixed: fixed.valid - }; - - if(!ignoreRotation) { - var rotatedAngle = $ax.visibility.getRotatedAngle(elementId); - if(rotatedAngle) { - rotation = rotatedAngle; - } else if(element && element.getAttribute('data-rotation')) { - rotation = Number(element.getAttribute('data-rotation')); - } else if($obj(elementId)) { - state = state || $ax.style.generateState(elementId); - style = style || $ax.style.computeFullStyle(elementId, state, $ax.adaptive.currentViewId); - rotation = style.rotation; - } else { - if (!trap) trap = _displayWidget($ax.repeater.removeSuffixFromElementId(elementId)); - rotation = $ax.move.getRotationDegreeFromElement(element); - } - if(rotation && rotation != 0) - boundingRect = $ax.public.fn.getBoundingRectForRotate(_populateBoundingRect(boundingRect), rotation); - } - - if (trap) trap(); - - return _populateBoundingRect(boundingRect); - }; - - //relative to the page - $ax.public.fn.pageBoundingRect = function (ignoreRotation, scrollableId) { - var boundingRect = this.offsetBoundingRect(ignoreRotation); - if(!boundingRect) return undefined; - - if(boundingRect.isFixed) return _populateBoundingRect(boundingRect); - - var loc = boundingRect.location; - - //var parents = []; - //var parObj = id.indexOf('text') != -1 ? axObj : axObj.parent; // When working with text id, parent widget is the ax obj we are dealing with, so that should be the first parent - //while ($ax.public.fn.IsContainer(parObj.type)) { - // parents.push($ax.getScriptIdFromPath([parObj.id], strippedId)); - // parObj = parObj.parent; - //} - //var otherParents = $ax('#' + id).getParents(true, ['item', 'repeater', 'dynamicPanel', 'layer'])[0]; - //for (var i = 0; i < otherParents.length; i++) { - // parents.push(otherParents[i]); - //} - - var elementId = this.getElementIds()[0]; - // var strippedId = $ax.repeater.removeSuffixFromElementId(id); - // var parObj = id.indexOf('text') != -1 ? axObj : axObj.parent; // When working with text id, parent widget is the ax obj we are dealing with, so that should be the first parent - var parentIds = []; - var parObj = $obj(elementId).parent; - while ($ax.public.fn.IsContainer(parObj.type)) { - parentIds.push($ax.getScriptIdFromPath([parObj.id], this.id)); - parObj = parObj.parent; - } - var otherParents = $ax('#' + elementId).getParents(true, ['item', 'repeater', 'dynamicPanel'])[0]; - for (var i = 0; i < otherParents.length; i++) { - parentIds.push(otherParents[i]); - } - - var parentScrollableId = scrollableId ? scrollableId.split('_')[0] : scrollableId; - for (var i = 0; i < parentIds.length; i++) { - //var parentId = $ax.visibility.getWidgetFromContainer(parents[0]); - //var parent = $ax.visibility.applyWidgetContainer(parentId, true); - //if(parent.length) { - //var parentId = parentIds[i]; - //var fixed = _fixedOffset(parentId, vert); - //if (fixed.valid) { - // loc += fixed.offset; - // break; - //} else loc += $ax.getNumFromPx(parent.css(prop)); - //} - - var parentId = parentIds[i]; - if (parentId == parentScrollableId) break; - var parentLoc = $ax('#' + parentId).offsetLocation(); - loc = { - x: loc.x + parentLoc.x, - y: loc.y + parentLoc.y, - left: loc.left + parentLoc.left, - top: loc.top + parentLoc.top, - } - var axObj = $obj(parentId); - if(axObj && axObj.fixedVertical) { - boundingRect.isFixed = true; - break; - } - } - - boundingRect.left = loc.x; - boundingRect.top = loc.y; - return _populateBoundingRect(boundingRect); - }; - - $ax.public.fn.viewportBoundingRect = function (scrollableId) { - var boundingRect = this.pageBoundingRect(true, scrollableId); - if (!boundingRect) return undefined; - - if(!boundingRect.isFixed) boundingRect.left = _bodyToWorld(boundingRect.left, false); - return _populateBoundingRect(boundingRect); - } - - $ax.public.fn.size = function () { - var boundingRect = this.offsetBoundingRect(true); - return boundingRect ? boundingRect.size : undefined; - - //var firstId = this.getElementIds()[0]; - //if(!firstId) return undefined; - - //var object = $ax.getObjectFromElementIdDisregardHex(firstId); - //if(object && (object.type == 'layer' || object.generateCompound)) { - // var boundingRect = $ax.public.fn.getWidgetBoundingRect(firstId); - // return { width: boundingRect.width, height: boundingRect.height }; - //} - - //var firstIdObject = $jobj(firstId); - //var trap = _displayWidget($ax.repeater.removeSuffixFromElementId(firstId)); - //var size = { width: firstIdObject.outerWidth(), height: firstIdObject.outerHeight() }; - //trap(); - //return size; - }; - - $ax.public.fn.width = function () { - var boundingRect = this.offsetBoundingRect(true); - return boundingRect ? boundingRect.width : undefined; - - //var firstId = this.getElementIds()[0]; - //if(!firstId) return undefined; - - //var object = $ax.getObjectFromElementIdDisregardHex(firstId); - //if (object && (object.type == 'layer' || object.generateCompound)) { - // var boundingRect = $ax.public.fn.getWidgetBoundingRect(firstId); - // return boundingRect.width; - //} - - //var firstIdObject = $jobj(firstId); - - //return firstIdObject.outerWidth(); - }; - - $ax.public.fn.height = function () { - var boundingRect = this.offsetBoundingRect(true); - return boundingRect ? boundingRect.height : undefined; - - //var firstId = this.getElementIds()[0]; - //if(!firstId) return undefined; - - //var object = $ax.getObjectFromElementIdDisregardHex(firstId); - //if (object && (object.type == 'layer' || object.generateCompound)) { - // var boundingRect = $ax.public.fn.getWidgetBoundingRect(firstId); - // return boundingRect.height; - //} - - //var firstIdObject = $jobj(firstId); - - //return firstIdObject.outerHeight(); - }; - - //this should replace locRelativeIgnoreLayer - $ax.public.fn.offsetLocation = function () { - var boundingRect = this.offsetBoundingRect(true); - return boundingRect ? boundingRect.location : undefined; - }; - - //$ax.public.fn.offsetLeft = function () { - // var boundingRect = this.offsetBoundingRect(); - // return boundingRect ? boundingRect.left : undefined; - //}; - - //$ax.public.fn.offsetTop = function () { - // var boundingRect = this.offsetBoundingRect(); - // return boundingRect ? boundingRect.top : undefined; - //}; - - $ax.public.fn.viewportLocation = function (scrollableId) { - var boundingRect = this.viewportBoundingRect(scrollableId); - return boundingRect ? boundingRect.location : undefined; - }; - - //$ax.public.fn.pageLeft = function () { - // var boundingRect = this.pageBoundingRect(); - // return boundingRect ? boundingRect.left : undefined; - //}; - - //$ax.public.fn.pageTop = function () { - // var boundingRect = this.pageBoundingRect(); - // return boundingRect ? boundingRect.top : undefined; - //}; - - //This is getting its position in the Editor - //It was needed because the widget would be contained so getting the position from jQuery would not be accurate - //This can use the editor values - //$ax.public.fn.locRelativeIgnoreLayer = function (vert) { - // var elementId = this.getElementIds()[0]; - // if(!elementId) return undefined; - - // var parents = this.getParents(true, '*')[0]; - - // for(var i = 0; i < parents.length; i++) { - // var type = $ax.getTypeFromElementId(parents[i]); - // if(!$axure.fn.IsLayer(type) && !$axure.fn.IsReferenceDiagramObject(type)) { - // var func = vert ? _getRelativeTop : _getRelativeLeft; - // return func(elementId, $jobj(parents[i])[0]); - // } - // } - // var axThis = $ax('#' + elementId); - // return vert ? axThis.top() : _bodyToWorld(axThis.left(), true); - //}; - - var _bodyToWorld = $axure.fn.bodyToWorld = function(x, from) { - var body = $('body'); - if (body.css('position') != 'relative') return x; - var offset = $ax.getNumFromPx(body.css('left')) + Math.max(0, ($(window).width() - body.width()) / 2); - if(from) offset *= -1; - return x + offset; - } - - $ax.public.fn.left = function (relative) { - return relative ? this.offsetLocation().left : this.viewportLocation().left; - - //var firstId = this.getElementIds()[0]; - //if(!firstId) return undefined; - - //var left = _getLoc(firstId, false, false, relative); - - //// If you are absolute, unless your are a pinned panel... - //if(relative || $obj(firstId) && $obj(firstId).fixedVertical) return left; - - //// ... or you are in one... - //var parentPanels = $ax('#' + firstId).getParents(true, 'dynamicPanel')[0]; - //for(var i = 0; i < parentPanels.length; i++) if ($obj(parentPanels[i]).fixedVertical) return left; - - //// ... you must convert from body to world coordinates - //return _bodyToWorld(left); - }; - - $ax.public.fn.top = function(relative) { - return relative ? this.offsetLocation().top : this.viewportLocation().top; - - //var firstId = this.getElementIds()[0]; - //return firstId && _getLoc(firstId, true, false, relative); - }; - - //var _getLoc = function(id, vert, high, relative) { - // var mathFunc = high ? 'max' : 'min'; - // var prop = vert ? 'top' : 'left'; - // var dim = vert ? 'height' : 'width'; - - // var obj = $jobj(id); - // var strippedId = $ax.repeater.removeSuffixFromElementId(id); - // var axObj = $obj(strippedId); - // var oldDisplay = obj.css('display'); - // var displaySet = false; - // if(oldDisplay == 'none') { - // obj.css('display', ''); - // displaySet = true; - // } - // var loc = Math.NaN; - // var rdo = axObj.type == $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE; - - // if (!rdo) loc = $ax.getNumFromPx(obj.css(prop)); - - // var fixed = _fixedOffset(id, vert); - // if(fixed.valid) loc = !vert && fixed.fullWidth ? 0 : fixed.offset; - // else if (!relative) { - // var parents = []; - // var parObj = id.indexOf('text') != -1 ? axObj : axObj.parent; // When working with text id, parent widget is the ax obj we are dealing with, so that should be the first parent - // while($ax.public.fn.IsContainer(parObj.type)) { - // parents.push($ax.getScriptIdFromPath([parObj.id], strippedId)); - // parObj = parObj.parent; - // } - // var otherParents = $ax('#' + id).getParents(true, ['item', 'repeater', 'dynamicPanel', 'layer'])[0]; - // for(var i = 0; i < otherParents.length; i++) { - // parents.push(otherParents[i]); - // } - - // for(var i = 0; i < parents.length; i++) { - // var parentId = $ax.visibility.getWidgetFromContainer(parents[i]); - // var parent = $ax.visibility.applyWidgetContainer(parentId, true); - - // // Layer may not have container, and will be at 0,0 otherwise. - // if (!parent.length) continue; - - // fixed = _fixedOffset(parentId, vert); - // if(fixed.valid) { - // loc += fixed.offset; - // break; // If fixed ignore any parents if there are any, they don't matter. - // } else loc += $ax.getNumFromPx(parent.css(prop)); - // } - // } - - // if (high) loc += obj[dim](); - - // // Special Layer code - // if (axObj.type == 'layer') { - // // If layer has a container, then use that. Otherwise must deal with children. Children can move in container after created, but ignoring for now. - // var container = $ax.visibility.applyWidgetContainer(id, true, true); - // if(container.length) loc += $ax.getNumFromPx(container.css(prop)); - // else loc += (_getChildLoc(axObj.objs, vert, high, dim, true, id) || 0); - // } - - // if(displaySet) obj.css('display', oldDisplay); - // return loc; - //}; - - //var _getChildLoc = function (children, vert, high, dim, root, path, itemId) { - // if (typeof (path) == 'string') { - // itemId = $ax.repeater.getItemIdFromElementId(path); - // path = $ax.getPathFromScriptId(path); - // path.pop(); // Remove object id, only want rdo path. - // } - // var mathFunc = high ? 'max' : 'min'; - // var childLoc = NaN; - // for (var i = 0; i < children.length; i++) { - // var childObj = children[i]; - // var childId = $ax.getElementIdFromPath([childObj.id], { relativeTo: path }); - // if (!childId) continue; - // childId = $ax.repeater.createElementId(childId, itemId); - // if($ax.public.fn.IsReferenceDiagramObject(childObj.type)) { - // path.push(childObj.id); - // var childProp = _getChildLoc($ax.pageData.masters[$obj(childId).masterId].diagram.objects, vert, high, dim, false, path, itemId); - // path.pop(); - // if(isNaN(childProp)) continue; - // } else if($ax.public.fn.IsLayer(childObj.type)) { - // childProp = _getChildLoc(childObj.objs, vert, high, dim, false, path, itemId); - // } else { - // if(!$ax.visibility.IsIdVisible(childId)) continue; - // childProp = $ax('#' + childId).locRelativeIgnoreLayer(vert); - // if(high) childProp += $jobj(childId)[dim](); - // } - - // if(isNaN(childLoc)) childLoc = childProp; - // else if(!isNaN(childProp)) childLoc = Math[mathFunc](childLoc, childProp); - // } - - // return root && isNaN(childLoc) ? 0 : childLoc; - //}; - - //var _fixedOffset = function (id, vert) { - // var axObj = $obj(id); - // //I think this is only for pinned panels? So why are we coming through here for rtps? - // if(!axObj) return { valid: false }; - - // var dim = vert ? 'height' : 'width'; - // var alignment = axObj['fixed' + (vert ? 'Vertical' : 'Horizontal')]; - // if(!alignment) return { valid: false }; - // var loc = 0; - - // // TODO: This returns 0 for width/height it or any parent is display none. Similar issue when using axquery width/height - // // TODO: Look into replacing this with axquery width/height and fixing that to use this hack. Potentially want to make js generic trapper. - // var trap = _displayWidget(id); - // var query = $jobj(id); - // var objSize = query[dim](); - // trap(); - - // if(alignment == 'center' || alignment == 'middle') { - // loc = $ax.getNumFromPx(query.css('margin-' + (vert ? 'top' : 'left'))); - // loc += ($(window)[dim]()) / 2; - // } else if(alignment == 'bottom' || alignment == 'right') { - // loc = $ax.getNumFromPx(query.css(vert ? 'bottom' : 'right')); - // loc = $(window)[dim]() - objSize - loc; // subract loc because margin here moves farther left/up as it gets bigger. - // } else { - // loc = $ax.getNumFromPx(query.css(vert ? 'top' : 'left')); - // } - - // var scrollKey = 'scroll' + (vert ? 'Top' : 'Left'); - // return { offset: $(window)[scrollKey]() + loc, valid: true, fullWidth: axObj.percentWidth == 1 }; - //}; - - var _displayWidget = function(id) { - var parents = $ax('#' + id).getParents(true, '*')[0]; - parents.push(id); // also need to show self - - var displayed = []; - for(var i = 0; i < parents.length; i++) { - var currId = parents[i]; - var currObj = $jobj(currId); - if(currObj.css('display') == 'none') { - currObj.css('display', 'block'); - displayed.push(currId); - } - } - - return function() { - for(var i = 0; i < displayed.length; i++) { - $jobj(displayed[i]).css('display', 'none'); - } - }; - } -}); diff --git a/web/main/static/resources/scripts/axure/doc.js b/web/main/static/resources/scripts/axure/doc.js deleted file mode 100644 index 9abe442..0000000 --- a/web/main/static/resources/scripts/axure/doc.js +++ /dev/null @@ -1,900 +0,0 @@ -$axure.internal(function($ax) { - var _pageData; - - - var _initializePageFragment = function(pageFragment, objIdToObject) { - var objectArrayHelper = function(objects, parent) { - for(var i = 0; i < objects.length; i++) { - diagramObjectHelper(objects[i], parent); - } - }; - - var diagramObjectHelper = function(diagramObject, parent) { - $ax.initializeObject('diagramObject', diagramObject); - objIdToObject[pageFragment.packageId + '~' + diagramObject.id] = diagramObject; - diagramObject.parent = parent; - diagramObject.owner = pageFragment; - diagramObject.scriptIds = []; - if(diagramObject.diagrams) { //dynamic panel - for(var i = 0; i < diagramObject.diagrams.length; i++) { - var diagram = diagramObject.diagrams[i]; - objectArrayHelper(diagram.objects, diagram); - } - } else if($ax.public.fn.IsLayer(diagramObject.type)) { - var layerObjs = diagramObject.objs; - objectArrayHelper(layerObjs, parent); - } - if(diagramObject.objects) objectArrayHelper(diagramObject.objects, diagramObject); - }; - objectArrayHelper(pageFragment.diagram.objects, pageFragment.diagram); - }; - - var _initalizeStylesheet = function(stylesheet) { - var stylesById = {}; - var customStyles = stylesheet.customStyles; - for(var key in customStyles) { - var style = customStyles[key]; - stylesById[style.id] = style; - } - var duplicateStyles = stylesheet.duplicateStyles; - for(var duplicateKey in duplicateStyles) { - stylesById[duplicateKey] = stylesById[duplicateStyles[duplicateKey]]; - } - - stylesheet.stylesById = stylesById; - }; - - - var _initializeDocumentData = function() { - _initalizeStylesheet($ax.document.stylesheet); - }; - - - var _initializePageData; - // ******* Dictionaries ******** // - (function() { - var scriptIdToParentLayer = {}; - var elementIdToObject = {}; - var scriptIdToObject = {}; - var scriptIdToRepeaterId = {}; - var repeaterIdToScriptIds = {}; - var repeaterIdToItemIds = {}; - var scriptIdToPath = {}; - var _scriptIds = []; - var elementIdToText = {}; - var radioGroupToSelectedElementId = {}; - _initializePageData = function() { - if(!_pageData || !_pageData.page || !_pageData.page.diagram) return; - - var objIdToObject = {}; - _initializePageFragment(_pageData.page, objIdToObject); - for(var masterId in _pageData.masters) { - var master = _pageData.masters[masterId]; - _initializePageFragment(master, objIdToObject); - } - - var _pathsToScriptIds = []; - _pathToScriptIdHelper(_pageData.objectPaths, [], _pathsToScriptIds, scriptIdToPath); - - for(var i = 0; i < _pathsToScriptIds.length; i++) { - var path = _pathsToScriptIds[i].idPath; - var scriptId = _pathsToScriptIds[i].scriptId; - - var packageId = _pageData.page.packageId; - if(path.length > 1) { - for(var j = 0; j < path.length - 1; j++) { - var rdoId = path[j]; - var rdo = objIdToObject[packageId + '~' + rdoId]; - packageId = rdo.masterId; - } - } - var diagramObject = objIdToObject[packageId + '~' + path[path.length - 1]]; - diagramObject.scriptIds[diagramObject.scriptIds.length] = scriptId; - - scriptIdToObject[scriptId] = diagramObject; - _scriptIds[_scriptIds.length] = scriptId; - } - - // Now map scriptIds to repeaters and layers - var mapScriptIdToRepeaterId = function(scriptId, repeaterId) { - scriptIdToRepeaterId[scriptId] = repeaterId; - var scriptIds = repeaterIdToScriptIds[repeaterId]; - if(scriptIds) scriptIds[scriptIds.length] = scriptId; - else repeaterIdToScriptIds[repeaterId] = [scriptId]; - }; - var mapScriptIdToLayerId = function(obj, layerId, path) { - var pathCopy = $ax.deepCopy(path); - pathCopy[path.length] = obj.id; - var scriptId = $ax.getScriptIdFromPath(pathCopy); - scriptIdToParentLayer[scriptId] = layerId; - } - var mapIdsToRepeaterAndLayer = function(path, objs, repeaterId) { - var pathCopy = $ax.deepCopy(path); - - for(var i = 0; i < objs.length; i++) { - var obj = objs[i]; - pathCopy[path.length] = obj.id; - var scriptId = $ax.getScriptIdFromPath(pathCopy); - // Rdo have no element on page and are not mapped to the repeater - if(repeaterId) mapScriptIdToRepeaterId(scriptId, repeaterId); - - if($ax.public.fn.IsDynamicPanel(obj.type)) { - for(var j = 0; j < obj.diagrams.length; j++) mapIdsToRepeaterAndLayer(path, obj.diagrams[j].objects, repeaterId); - } else if($ax.public.fn.IsReferenceDiagramObject(obj.type)) { - mapIdsToRepeaterAndLayer(pathCopy, $ax.pageData.masters[obj.masterId].diagram.objects, repeaterId); - } else if($ax.public.fn.IsRepeater(obj.type)) { - mapScriptIdToRepeaterId(scriptId, scriptId); - mapIdsToRepeaterAndLayer(path, obj.objects, scriptId); - } else if($ax.public.fn.IsLayer(obj.type)) { - var layerObjs = obj.objs; - for(var j = 0; j < layerObjs.length; j++) { - mapScriptIdToLayerId(layerObjs[j], scriptId, path); - } - mapIdsToRepeaterAndLayer(path, layerObjs, repeaterId); - } else if(obj.objects && obj.objects.length) { - if(repeaterId) { - for(var j = 0; j < obj.objects.length; j++) { - mapIdsToRepeaterAndLayer(path, obj.objects, repeaterId); - } - } - } - } - }; - mapIdsToRepeaterAndLayer([], $ax.pageData.page.diagram.objects); - }; - - - $ax.getPathFromScriptId = function(scriptId) { - var reversedPath = []; - var path = scriptIdToPath[scriptId]; - while(path && path.uniqueId) { - reversedPath[reversedPath.length] = path.uniqueId; - path = path.parent; - } - return reversedPath.reverse(); - }; - - var _getScriptIdFromFullPath = function(path) { - var current = $ax.pageData.objectPaths; - for(var i = 0; i < path.length; i++) { - current = current[path[i]]; - if(!current) return current; - } - return current && current.scriptId; - }; - - - var _getScriptIdFromPath = function(path, relativeTo, includeLimbo) { - var relativePath = []; - var includeMasterInPath = false; - if(relativeTo) { - var relativeToScriptId; - if(relativeTo.srcElement) { //this is eventInfo - relativeToScriptId = $ax.repeater.getScriptIdFromElementId(relativeTo.srcElement); - includeMasterInPath = relativeTo.isMasterEvent; - } else if(typeof relativeTo === 'string') { //this is an element id - relativeToScriptId = relativeTo; - } - - if(relativeToScriptId) { - relativePath = $ax.getPathFromScriptId(relativeToScriptId); - if(!includeMasterInPath) relativePath = relativePath.slice(0, relativePath.length - 1); - } else if(relativeTo instanceof Array) { //this is a path - relativePath = relativeTo; - } - } - var fullPath = relativePath.concat(path); - var scriptId = _getScriptIdFromFullPath(fullPath); - return (includeLimbo || !$ax.visibility.isScriptIdLimbo(scriptId)) && scriptId; - }; - $ax.getScriptIdFromPath = _getScriptIdFromPath; - - var _getElementIdsFromPath = function(path, eventInfo) { - var scriptId = _getScriptIdFromPath(path, eventInfo); - if(!scriptId) return []; - // Don't need placed check hear. If unplaced, scriptId will be undefined and exit out before here. - return $ax.getElementIdsFromEventAndScriptId(eventInfo, scriptId); - }; - $ax.getElementIdsFromPath = _getElementIdsFromPath; - - var _getElementIdFromPath = function(path, params, includeLimbo) { - var scriptId = _getScriptIdFromPath(path, params.relativeTo, includeLimbo); - if(!scriptId) return scriptId; - - var itemNum = params.itemNum; - if(params.relativeTo && typeof params.relativeTo === 'string') { - if($jobj(params.relativeTo)) itemNum = $ax.repeater.getItemIdFromElementId(params.relativeTo); - } - return $ax.repeater.createElementId(scriptId, itemNum); - }; - $ax.getElementIdFromPath = _getElementIdFromPath; - - var _getElementsIdFromEventAndScriptId = function(eventInfo, scriptId) { - var itemId = eventInfo && $ax.repeater.getItemIdFromElementId(eventInfo.srcElement); - var target = false; - // Try to get itemId from target if you can't get it from source. - if(!itemId) { - itemId = eventInfo && eventInfo.targetElement && $ax.repeater.getItemIdFromElementId(eventInfo.targetElement); - if(itemId) target = true; - } - - var parentRepeater = $ax.getParentRepeaterFromScriptId(scriptId); - if(parentRepeater && scriptId != parentRepeater) { - if(itemId && (!eventInfo || parentRepeater == $ax.getParentRepeaterFromScriptId($ax.repeater.getScriptIdFromElementId(target ? eventInfo.targetElement : eventInfo.srcElement)))) { - return [$ax.repeater.createElementId(scriptId, itemId)]; - } - var elementIds = []; - var itemIds = $ax.getItemIdsForRepeater(parentRepeater); - if(!itemIds) return []; - - for(var i = 0; i < itemIds.length; i++) elementIds[i] = $ax.repeater.createElementId(scriptId, itemIds[i]); - return elementIds; - } - return [scriptId]; - }; - $ax.getElementIdsFromEventAndScriptId = _getElementsIdFromEventAndScriptId; - - var _getSrcElementIdFromEvent = function(event) { - var currentQuery = $(event.srcElement || event.target); - while(currentQuery && currentQuery.length && (!$obj(currentQuery.attr('id')) || $jobj(currentQuery.attr('id')).hasClass('text'))) { - currentQuery = currentQuery.parent(); - }; - return currentQuery.attr('id'); - }; - $ax.getSrcElementIdFromEvent = _getSrcElementIdFromEvent; - - var _getEventInfoFromEvent = function(event, skipShowDescriptions, elementId) { - var eventInfo = {}; - eventInfo.srcElement = elementId; - eventInfo.now = new Date(); - - if(event != null) { - //elementId can be empty string, so can't simple use "or" assignment here. - eventInfo.srcElement = elementId || elementId == '' ? elementId : _getSrcElementIdFromEvent(event); - eventInfo.which = event.which; - - // When getting locations in mobile, need to extract the touch object to get the mouse location attributes - var mouseEvent = (event.originalEvent && event.originalEvent.changedTouches && event.originalEvent.changedTouches[0]) || event.originalEvent; - if(mouseEvent && !mouseEvent.type) mouseEvent.type = event.type; - - if(skipShowDescriptions) eventInfo.skipShowDescriptions = true; - - // Always update mouse location if possible - $ax.event.updateMouseLocation(mouseEvent); - } - - // Always set event info about cursor - var _cursor = eventInfo.cursor = {}; - _cursor.x = $ax.mouseLocation.x; - _cursor.y = $ax.mouseLocation.y; - - var body = $('body'); - if(body.css('position') == 'relative') { - _cursor.x -= ($ax.getNumFromPx(body.css('left')) + Math.max(0, ($(window).width() - body.width()) / 2)); - } - - eventInfo.pageX = _cursor.x + 'px'; - eventInfo.pageY = _cursor.y + 'px'; - - // Do Keyboard Info - eventInfo.keyInfo = $ax.event.keyState(); - - eventInfo.window = $ax.getWindowInfo(); - - eventInfo.thiswidget = _getWidgetInfo(eventInfo.srcElement); - eventInfo.item = _getItemInfo(eventInfo.srcElement); - eventInfo.dragInfo = $ax.drag.GetWidgetDragInfo(); - - return eventInfo; - }; - $ax.getEventInfoFromEvent = _getEventInfoFromEvent; - - $ax.getBasicEventInfo = function() { - var eventInfo = {}; - eventInfo.now = new Date(); - eventInfo.window = $ax.getWindowInfo(); - eventInfo.cursor = { x: 0, y: 0}; - return eventInfo; - - }; - - //var _getWindowInfo = function() { - // var win = {}; - // win.width = $(window).width(); - // win.height = $(window).height(); - // win.scrollx = $(window).scrollLeft(); - // win.scrolly = $(window).scrollTop(); - // return win; - //}; - //$ax.getWindowInfo = _getWindowInfo; - - var repeaterInfoCache = []; - $ax.cacheRepeaterInfo = function(repeaterId, repeaterInfo) { - repeaterInfoCache[repeaterId] = repeaterInfo; - } - $ax.removeCachedRepeaterInfo = function(repeaterId) { - repeaterInfoCache[repeaterId] = undefined; - } - - var _getItemInfo = function(elementId) { - if(!elementId) return { valid: false }; - - elementId = _getParentElement(elementId); - - var index = $ax.repeater.getItemIdFromElementId(elementId); - if(!index) return { valid: false }; - - var item = { valid: true }; - - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - var repeaterId = $ax.getParentRepeaterFromScriptId(scriptId); - item.repeater = repeaterInfoCache[repeaterId] ? repeaterInfoCache[repeaterId] : _getWidgetInfo(repeaterId); - $ax.repeater.setDisplayProps(item, repeaterId, index); - item.ismarked = $ax.repeater.isEditItem(repeaterId, index); - item.isvisible = Boolean($jobj(elementId).length); - - return item; - }; - $ax.getItemInfo = _getItemInfo; - - var _getWidgetInfo = function(elementId) { - if(!elementId) return { valid: false }; - - elementId = _getParentElement(elementId); - - //var elementAxQuery = $ax('#' + elementId); - var elementQuery = $jobj(elementId); - var obj = $obj(elementId); - var widget = { valid: true, isWidget: true, obj: obj, elementQuery: elementQuery, isLayer: $ax.public.fn.IsLayer(obj.type) }; - widget.elementId = elementId; - widget.name = widget.label = (elementQuery.data('label') ? elementQuery.data('label') : ''); - //widget.text = $ax('#' + elementId).text(); - widget.opacity = Number(elementQuery.css('opacity')) * 100; - //widget.rotation = $ax.move.getRotationDegree(widget.elementId); - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - var repeaterId = $ax.getParentRepeaterFromScriptId(scriptId); - if(repeaterId) widget.repeater = $ax.public.fn.IsRepeater(obj.type) ? widget : _getWidgetInfo(repeaterId); - - // Right now only dynamic panel can scroll - if($ax.public.fn.IsDynamicPanel(obj.type)) { - var stateId = $ax.visibility.GetPanelState(elementId); - //can be empty when refreshing repeater and applying filter - if(stateId) { - var stateQuery = $('#' + stateId); - widget.scrollx = stateQuery.scrollLeft(); - widget.scrolly = stateQuery.scrollTop(); - //widget.stateQuery = stateQuery; - } - } else { - widget.scrollx = 0; - widget.scrolly = 0; - } - - // repeater only props - if($ax.public.fn.IsRepeater(obj.type)) { - widget.visibleitemcount = repeaterIdToItemIds[scriptId] ? repeaterIdToItemIds[scriptId].length : $ax.repeater.getVisibleDataCount(scriptId); - widget.itemcount = $ax.repeater.getFilteredDataCount(scriptId); - widget.datacount = $ax.repeater.getDataCount(scriptId); - widget.pagecount = $ax.repeater.getPageCount(scriptId); - widget.pageindex = $ax.repeater.getPageIndex(scriptId); - } - - // Get widget info funcs - //widget.elementAxQuery = function () { - // return this.elementAxQueryProp || (this.elementAxQueryProp = $ax('#' + this.elementId)); - //} - - //widget.isFitToContent = function () { - // if (this.isFitToContentProp === undefined) { - // if (!this.stateQuery) this.isFitToContentProp = false; - // else this.isFitToContentProp = $ax.dynamicPanelManager.isIdFitToContent(this.elementId); - // } - // return this.isFitToContentProp; - //} - - widget.x = function () { return this.getProp('x'); } - widget.y = function () { return this.getProp('y'); } - widget.pagex = function () { return this.getProp('pagex'); } - widget.pagey = function () { return this.getProp('pagey'); } - widget.width = function () { return this.getProp('width'); } - widget.height = function () { return this.getProp('height'); } - widget.left = function () { return this.x(); } - widget.top = function () { return this.y(); } - widget.right = function () { return this.x() + this.width(); } - widget.bottom = function () { return this.y() + this.height(); } - widget.rotation = function () { return this.getProp('rotation'); } - widget.text = function () { return this.getProp('text'); } - - widget.getProp = function (prop) { - var propName = prop + 'Prop'; - if (typeof (this[propName]) != 'undefined') return this[propName]; - return this[propName] = this.cacheProp(prop); - }; - - widget.cacheProp = function (prop) { - - if(prop == 'x' || prop == 'y' || prop == 'width' || prop == 'height') { - var boundingRect = $ax('#' + this.elementId).offsetBoundingRect(true); - this.xProp = boundingRect.left; - this.yProp = boundingRect.top; - this.widthProp = boundingRect.width; - this.heightProp = boundingRect.height; - } - - if(prop == 'pagex' || prop == 'pagey') { - var viewportLocation = $ax('#' + this.elementId).viewportLocation(); - this.pagexProp = viewportLocation.left; - this.pageyProp = viewportLocation.top; - } - - if(prop == 'rotation') { - this.rotationProp = $ax.move.getRotationDegree(this.elementId); - } - - if (prop == 'text') { - this.textProp = $ax('#' + this.elementId).text(); - } - - return this[prop + 'Prop']; - - //// I'm keeping the returned undefineds the same as before, but really I could probably return undefined right away if elementQuery is empty - //if (this.isLayer) { - // if (prop == 'pagex' || prop == 'pagey') { - // if (this.elementQuery.length > 0) { - // if (prop == 'pagex') return this.elementAxQuery().left(); - // else return this.elementAxQuery().top(); - // } - // return undefined; // Otherwise, it is undefined as there is no element - // } - // var boundingRect = $ax.public.fn.getWidgetBoundingRect(this.elementId); - // this.xProp = boundingRect.left; - // this.yProp = boundingRect.top; - // this.widthProp = boundingRect.width; - // this.heightProp = boundingRect.height; - // return this[prop + 'Prop']; - //} - - //if (this.elementQuery.length <= 0) return prop == 'x' || prop == 'y' ? 0 : undefined; - - //switch (prop) { - // case 'x': return this.elementAxQuery().locRelativeIgnoreLayer(false); - // case 'y': return this.elementAxQuery().locRelativeIgnoreLayer(true); - // case 'pagex': return this.elementAxQuery().left(); - // case 'pagey': return this.elementAxQuery().top(); - //} - - //var val = this.elementAxQuery()[prop](); - //if (this.isFitToContent()) val = this.stateQuery[prop](); - - //return val; - }; - - //widget.leftfixed = function() { this.getFixed('left'); } - //widget.topfixed = function() { this.getFixed('top'); } - //widget.rightfixed = function() { this.getFixed('right'); } - //widget.bottomfixed = function() { this.getFixed('bottom'); } - - //widget.isFixed = function() { - // if(this.isFixedProp === undefined) this.isFixedProp = this.elementQuery.css('position') == 'fixed)'; - // return this.isFixedProp; - //} - - //widget.getFixed = function (prop) { - // var fixed = prop + 'fixedProp'; - // if(!this.isFixed()) widget[fixed] = widget[prop](); - // if(widget[fixed] === undefined) { - - // if(prop == 'left' || prop == 'right') { - // if(this.windowScrollX === undefined) this.windowScrollX = $(window).scrollLeft(); - // var windowScroll = this.windowScrollX; - // } else { - // if(this.windowScrollY === undefined) this.windowScrollY = $(window).scrollTop(); - // windowScroll = this.windowScrollY; - // } - // widget[fixed] = widget[prop]() - windowScroll; - // } - // return widget[fixed]; - //} - - return widget; - }; - $ax.getWidgetInfo = _getWidgetInfo; - - $ax.GetTextPanelId = function (id, create) { - if(!$ax('#' + id).SupportsRichText()) return ''; - var buttonShape = $ax.GetButtonShape(id); - var panelDiv = buttonShape.find('.text')[0]; - if(!panelDiv) { - if(!create) return ""; - - var adaptiveId = $ax.adaptive.currentViewId; - var newId = id + "_text"; - //var newDiv = $('<div id="' + newId + '" class="text" style="visibility: inherit; position: absolute"></div>'); - var newDiv = $('<div id="' + newId + '" class="text' + (adaptiveId ? (' ' + adaptiveId) : '') + '" style="visibility: inherit; position: absolute"><p><span></span></p></div>'); - buttonShape.append(newDiv); - - $ax.style.setAdaptiveStyle(id, $ax.style.computeAllOverrides(id, undefined, $ax.style.generateState(id), adaptiveId)); - - panelDiv = newDiv[0]; - } - - return panelDiv.id; - } - - $ax.GetParentIdFromLink = function(id) { - return $ax.GetShapeIdFromText($jobj(id).parentsUntil('.text').parent().attr('id')); - }; - - $ax.GetButtonShapeId = function(id) { - var obj = $obj(id); - switch(obj.type) { - case $ax.constants.TREE_NODE_OBJECT_TYPE: - return obj.buttonShapeId ? $ax.getElementIdFromPath([obj.buttonShapeId], { relativeTo: id }) : ""; - case $ax.constants.LINK_TYPE: - return ""; - default: - return id; - } - }; - - $ax.GetButtonShape = function(id) { - return $jobj($ax.GetButtonShapeId(id)); - }; - - $ax.GetShapeIdFromText = function(id) { - if(!id) return undefined; // this is to prevent an infinite loop. - - var current = document.getElementById(id); - if(!current) return undefined; - current = current.parentElement; - while(current && current.tagName != 'BODY') { - var currentId = current.id; - if(currentId && currentId != 'base') return $ax.visibility.getWidgetFromContainer(currentId); - current = current.parentElement; - } - - return undefined; - }; - - $ax.GetImageIdFromShape = function(id) { - var image = $ax.GetButtonShape(id).find('img[id$=img]'); - if(!image.length) image = $jobj(id).find('img[id$=image_sketch]'); - return image.attr('id'); - }; - - var _getParentElement = $ax.getParentElement = function(elementId) { - var obj = $obj(elementId); - while(obj.isContained) { - var path = $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(elementId)); - var itemId = $ax.repeater.getItemIdFromElementId(elementId); - path[path.length - 1] = obj.parent.id; - elementId = $ax.getElementIdFromPath(path, { itemNum: itemId }); - obj = $obj(elementId); - } - - return elementId; - }; - - $ax.addItemIdToRepeater = function(itemId, repeaterId) { - var itemIds = repeaterIdToItemIds[repeaterId]; - if(itemIds) itemIds[itemIds.length] = itemId; - else repeaterIdToItemIds[repeaterId] = [itemId]; - - var scriptIds = repeaterIdToScriptIds[repeaterId]; - for(var i = 0; i < scriptIds.length; i++) elementIdToObject[$ax.repeater.createElementId(scriptIds[i], itemId)] = $ax.getObjectFromScriptId(scriptIds[i]); - }; - - $ax.getAllElementIds = function() { - var elementIds = []; - for(var i = 0; i < _scriptIds.length; i++) { - var scriptId = _scriptIds[i]; - var repeaterId = scriptIdToRepeaterId[scriptId]; - if(repeaterId && repeaterId != scriptId) { - var itemIds = repeaterIdToItemIds[repeaterId] || []; - for(var j = 0; j < itemIds.length; j++) elementIds[elementIds.length] = $ax.repeater.createElementId(scriptId, itemIds[j]); - } else elementIds[elementIds.length] = scriptId; - } - return elementIds; - }; - - $ax.getAllScriptIds = function() { - return _scriptIds; - }; - - $ax.getObjectFromElementId = function(elementId) { - return $ax.getObjectFromScriptId($ax.repeater.getScriptIdFromElementId(elementId)); - }; - - $ax.getObjectFromScriptId = function(scriptId) { - return scriptIdToObject[scriptId]; - }; - - $ax.getParentRepeaterFromElementId = function(elementId) { - return $ax.getParentRepeaterFromScriptId($ax.repeater.getScriptIdFromElementId(elementId)); - }; - - $ax.getParentRepeaterFromElementIdExcludeSelf = function (elementId) { - var repeaterId = $ax.getParentRepeaterFromElementId(elementId); - return repeaterId != elementId ? repeaterId : undefined; - }; - - $ax.getParentRepeaterFromScriptId = function(scriptId) { - return scriptIdToRepeaterId[scriptId]; - }; - - var _getChildScriptIdsForRepeater = function(repeaterId) { - return repeaterIdToScriptIds[repeaterId]; - }; - - var _getItemIdsForRepeater = function(repeaterId) { - return repeaterIdToItemIds[repeaterId] || []; - }; - $ax.getItemIdsForRepeater = _getItemIdsForRepeater; - - var _clearItemIdsForRepeater = function(repeaterId) { - repeaterIdToItemIds[repeaterId] = []; - }; - $ax.clearItemsForRepeater = _clearItemIdsForRepeater; - - $ax.getChildElementIdsForRepeater = function(repeaterId) { - var scriptIds = _getChildScriptIdsForRepeater(repeaterId); - var itemIds = _getItemIdsForRepeater(repeaterId); - - var retVal = []; - if(!itemIds || !scriptIds) return retVal; - - for(var i = 0; i < scriptIds.length; i++) { - for(var j = 0; j < itemIds.length; j++) { - retVal[retVal.length] = $ax.repeater.createElementId(scriptIds[i], itemIds[j]); - } - } - return retVal; - }; - - $ax.getRdoParentFromElementId = function(elementId) { - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - var rdoId = scriptIdToPath[scriptId].parent.scriptId; - if($ax.getParentRepeaterFromScriptId(rdoId)) rdoId = $ax.repeater.createElementId(rdoId, $ax.repeater.getItemIdFromElementId(elementId)); - return rdoId; - }; - - $ax.getLayerParentFromElementId = function (elementId) { - var itemId = $ax.repeater.getItemIdFromElementId(elementId); - var scriptId = scriptIdToParentLayer[$ax.repeater.getScriptIdFromElementId(elementId)]; - return $ax.getParentRepeaterFromElementId(scriptId) ? $ax.repeater.createElementId(scriptId, itemId) : scriptId; - } - - $ax.updateElementText = function(elementId, text) { - elementIdToText[elementId] = text; - }; - - $ax.hasElementTextChanged = function(elementId, text) { - return elementIdToText[elementId] != text; - }; - - $ax.updateRadioButtonSelected = function(group, elementId) { - var old = radioGroupToSelectedElementId[group]; - radioGroupToSelectedElementId[group] = elementId; - return old; - }; - - $ax.hasRadioButtonSelectedChanged = function(group, elementId) { - return radioGroupToSelectedElementId[group] != elementId; - }; - })(); - - //Recursively populates fullPathArray with: - // [ { idPath, scriptId }, ... ] - //for every scriptId in the object - //also populates an object of scriptId -> path - var _pathToScriptIdHelper = function(currentPath, currentChain, fullPathArray, scriptIdToPath) { - for(var key in currentPath) { - if(key != "scriptId") { - var nextPath = currentPath[key]; - _pathToScriptIdHelper(nextPath, currentChain.concat(key), fullPathArray, scriptIdToPath); - nextPath.parent = currentPath; - nextPath.uniqueId = key; - } else { - fullPathArray[fullPathArray.length] = { idPath: currentChain, scriptId: currentPath.scriptId }; - scriptIdToPath[currentPath.scriptId] = currentPath; - } - } - }; - - $ax.public.loadCurrentPage = $ax.loadCurrentPage = function(pageData) { - $ax.pageData = _pageData = pageData; - _initializePageData(); - }; - - $ax.public.loadDocument = $ax.loadDocument = function(document) { - $ax.document = document; - _initializeDocumentData(); - }; - - - /** - Navigates to a page - - - */ - $ax.public.navigate = $ax.navigate = function(to) { //url, includeVariables, type) { - var targetUrl; - if(typeof (to) === 'object') { - targetUrl = !to.includeVariables ? to.url : $ax.globalVariableProvider.getLinkUrl(to.url, to.useGlobalVarNameInUrl); - - if(to.target == "new") { - window.open(targetUrl, ""); - } else if(to.target == "popup") { - var features = _getPopupFeatures(to.popupOptions); - window.open(targetUrl, "", features); - } else { - var targetLocation = window.location; - if(to.target == "current") { - } else if(to.target == "parent") { - if(!top.opener) return; - targetLocation = top.opener.window.location; - } else if(to.target == "parentFrame") { - targetLocation = parent.location; - } else if(to.target == "frame") { - // targetLocation = to.frame.contentWindow.location; - $(to.frame).attr('src', targetUrl || 'about:blank'); - return; - } - - if (!_needsReload(targetLocation, to.url)) { - targetLocation.href = targetUrl || 'about:blank'; - } else { - targetLocation.href = $axure.utils.getReloadPath() + "#" + encodeURI(targetUrl); - } - } - } else { - $ax.navigate({ - url: to, - target: "current", - includeVariables: arguments[1] - }); - } - }; - - var _needsReload = function(oldLocation, newBaseUrl) { - var reload = false; - try { - var oldUrl = oldLocation.href; - var oldBaseUrl = oldUrl.split("#")[0]; - var lastslash = oldBaseUrl.lastIndexOf("/"); - if(lastslash > 0) { - oldBaseUrl = oldBaseUrl.substring(lastslash + 1, oldBaseUrl.length); - if(oldBaseUrl == encodeURI(newBaseUrl)) { - reload = true; - } - } - } catch(e) { - } - return reload; - }; - - var _getPopupFeatures = function(options) { - var defaultOptions = { - toolbar: true, - scrollbars: true, - location: true, - status: true, - menubar: true, - directories: true, - resizable: true, - centerwindow: true, - left: -1, - top: -1, - height: -1, - width: -1 - }; - - var selectedOptions = $.extend({}, defaultOptions, options); - - var optionsList = []; - optionsList.push('toolbar=' + (selectedOptions.toolbar ? 'yes' : 'no')); - optionsList.push('scrollbars=' + (selectedOptions.scrollbars ? 'yes' : 'no')); - optionsList.push('location=' + (selectedOptions.location ? 'yes' : 'no')); - optionsList.push('status=' + (selectedOptions.status ? 'yes' : 'no')); - optionsList.push('menubar=' + (selectedOptions.menubar ? 'yes' : 'no')); - optionsList.push('directories=' + (selectedOptions.directories ? 'yes' : 'no')); - optionsList.push('resizable=' + (selectedOptions.resizable ? 'yes' : 'no')); - - if(selectedOptions.centerwindow == false) { - if(selectedOptions.left > -1) { - optionsList.push('left=' + selectedOptions.left); - } - - if(selectedOptions.top > -1) { - optionsList.push('top=' + selectedOptions.top); - } - } - - var height = 0; - var width = 0; - if(selectedOptions.height > 0) { - optionsList.push('height=' + selectedOptions.height); - height = selectedOptions.height; - } - - if(selectedOptions.width > 0) { - optionsList.push('width=' + selectedOptions.width); - width = selectedOptions.width; - } - - var features = optionsList.join(','); - if(selectedOptions.centerwindow) { - var winl = (window.screen.width - width) / 2; - var wint = (window.screen.height - height) / 2; - features = features + ',left=' + winl + ',top=' + wint; - } - - return features; - }; - - /** - Closes a window - - - */ - $ax.public.closeWindow = $ax.closeWindow = function() { - parent.window.close(); - }; - - /** - Goes back - - - */ - $ax.public.back = $ax.back = function() { - window.history.go(-1); - }; - - /** - Reloads the current page. - # includeVariables: true if it should re-include the variables when the page is reloaded - */ - $ax.public.reload = $ax.reload = function(includeVariables) { - var targetUrl = (includeVariables === false) - ? $axure.utils.getReloadPath() + "#" + encodeURI($ax.pageData.url) - : $axure.utils.getReloadPath() + "#" + encodeURI($ax.globalVariableProvider.getLinkUrl($ax.pageData.url)); - window.location.href = targetUrl; - }; - - /** - Sets a variable. - # name: The name of the global variable to set - # value: The value that should be set - */ - $ax.public.setGlobalVariable = $ax.setGlobalVariable = function(name, value) { - if(!name || !value) { - return; - } - - $ax.globalVariableProvider.setVariableValue(name, value); - }; - - /** - Gets the value of a global variable - # name: The name of the global variable value to get - */ - $ax.public.getGlobalVariable = $ax.getGlobalVariable = function(name) { - $ax.globalVariableProvider.getVariableValue(name); - }; - - $ax.getObjectFromElementIdDisregardHex = function (elementId) { - var elementIdInput = elementId.charAt(0) == '#' ? elementId.substring(1) : elementId; - return this.getObjectFromElementId(elementIdInput); - } - - - $ax.getTypeFromElementId = function(elementId) { - var obj = this.getObjectFromElementIdDisregardHex(elementId); - return obj && obj.type; - }; - - $ax.getNumFromPx = function(pxNum) { - return Number(pxNum.replace('px', '')); - } - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/drag.js b/web/main/static/resources/scripts/axure/drag.js deleted file mode 100644 index da15742..0000000 --- a/web/main/static/resources/scripts/axure/drag.js +++ /dev/null @@ -1,278 +0,0 @@ -$axure.internal(function($ax) { - var widgetDragInfo = new Object(); - var _drag = {}; - $ax.drag = _drag; - - $ax.drag.GetWidgetDragInfo = function() { - return $.extend({}, widgetDragInfo); - }; - - $ax.drag.StartDragWidget = function(event, id) { - $ax.setjBrowserEvent(jQuery.Event(event)); - //we should only start drag on one target, otherwise the _dragWidget and _stopDragWidget events from multiple targets will be conflicted - if(event.donotdrag || widgetDragInfo.started) return; - - var x, y; - var tg; - if(IE_10_AND_BELOW) { - x = window.event.clientX + window.document.documentElement.scrollLeft + window.document.body.scrollLeft; - y = window.event.clientY + window.document.documentElement.scrollTop + window.document.body.scrollTop; - tg = window.event.srcElement; - } else { - if(event.changedTouches) { - x = event.changedTouches[0].pageX; - y = event.changedTouches[0].pageY; - } else { - x = event.pageX; - y = event.pageY; - event.preventDefault(); - } - tg = event.target; - } - - widgetDragInfo.started = true; - widgetDragInfo.hasDragged= false; - widgetDragInfo.widgetId = id; - widgetDragInfo.cursorStartX = x; - widgetDragInfo.cursorStartY = y; - widgetDragInfo.lastX = x; - widgetDragInfo.lastY = y; - widgetDragInfo.currentX = x; - widgetDragInfo.currentY = y; - - widgetDragInfo.movedWidgets = new Object(); - widgetDragInfo.startTime = (new Date()).getTime(); - widgetDragInfo.targetWidget = tg; - - var movedownName = IE_10_AND_BELOW && $ax.features.supports.windowsMobile ? - $ax.features.eventNames.mouseDownName : $ax.features.eventNames.mouseMoveName; - $ax.event.addEvent(document, movedownName, _dragWidget, true); - $ax.event.addEvent(document, $ax.features.eventNames.mouseUpName, _stopDragWidget, true); - - //$ax.legacy.SuppressBubble(event); - }; - - var _dragWidget = function(event) { - $ax.setjBrowserEvent(jQuery.Event(event)); - - var x, y; - if(IE_10_AND_BELOW) { - x = window.event.clientX + window.document.documentElement.scrollLeft + window.document.body.scrollLeft; - y = window.event.clientY + window.document.documentElement.scrollTop + window.document.body.scrollTop; - } else { - if(event.changedTouches) { - x = event.changedTouches[0].pageX; - y = event.changedTouches[0].pageY; - //allow scroll (defaults) if only swipe events have cases and delta x is less than 5px and not blocking scrolling - var deltaX = x - widgetDragInfo.currentX; - var target = window.document.getElementById(widgetDragInfo.widgetId); - if($ax.event.hasSyntheticEvent(widgetDragInfo.widgetId, "onDrag") || $ax.event.hasSyntheticEvent(widgetDragInfo.widgetId, "onSwipeUp") || - $ax.event.hasSyntheticEvent(widgetDragInfo.widgetId, "onSwipeDown") || (deltaX * deltaX) > 25 - || ($ax.document.configuration.preventScroll && $ax.legacy.GetScrollable(target) == window.document.body)) { - event.preventDefault(); - } - } else { - x = event.pageX; - y = event.pageY; - } - } - widgetDragInfo.xDelta = x - widgetDragInfo.currentX; - widgetDragInfo.yDelta = y - widgetDragInfo.currentY; - widgetDragInfo.lastX = widgetDragInfo.currentX; - widgetDragInfo.lastY = widgetDragInfo.currentY; - widgetDragInfo.currentX = x; - widgetDragInfo.currentY = y; - - widgetDragInfo.currentTime = (new Date()).getTime(); - - // $ax.legacy.SuppressBubble(event); - - if(!widgetDragInfo.hasDragged) { - widgetDragInfo.hasDragged = true; - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onDragStart"); - - //only update to move cursor is we are moving objects - if($ax.event.hasSyntheticEvent(widgetDragInfo.widgetId, "onDrag")) { - widgetDragInfo.cursorChanged = true; - widgetDragInfo.oldBodyCursor = window.document.body.style.cursor; - window.document.body.style.cursor = 'move'; - var widget = window.document.getElementById(widgetDragInfo.widgetId); - widgetDragInfo.oldCursor = widget.style.cursor; - widget.style.cursor = 'move'; - //need to do this in order to change the cursor under nice scroll - var niceScrollContainer = $ax.adaptive.getNiceScrollContainer(widget); - if(niceScrollContainer) { - widgetDragInfo.oldNiceScrollContainerCursor = niceScrollContainer.style.cursor; - niceScrollContainer.style.cursor = 'move'; - } - } - } - - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onDrag"); - }; - - var _suppressClickAfterDrag = function(event) { - _removeSuppressEvents(); - - $ax.legacy.SuppressBubble(event); - }; - - var _removeSuppressEvents = function () { - if(IE_10_AND_BELOW) { - $ax.event.removeEvent(event.srcElement, 'click', _suppressClickAfterDrag, undefined, true); - $ax.event.removeEvent(widgetDragInfo.targetWidget, 'mousemove', _removeSuppressEvents, undefined, true); - } else { - $ax.event.removeEvent(document, "click", _suppressClickAfterDrag, true); - $ax.event.removeEvent(document, 'mousemove', _removeSuppressEvents, true); - } - }; - - var _stopDragWidget = function(event) { - $ax.setjBrowserEvent(jQuery.Event(event)); - - var tg; - - - var movedownName = IE_10_AND_BELOW && $ax.features.supports.windowsMobile ? - $ax.features.eventNames.mouseDownName : $ax.features.eventNames.mouseMoveName; - $ax.event.removeEvent(document, movedownName, _dragWidget, true); - $ax.event.removeEvent(document, $ax.features.eventNames.mouseUpName, _stopDragWidget, true); - - tg = IE_10_AND_BELOW ? window.event.srcElement : event.target; - - if(widgetDragInfo.hasDragged) { - widgetDragInfo.currentTime = (new Date()).getTime(); - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onDragDrop"); - - if($ax.globalVariableProvider.getVariableValue('totaldragx') < -30 && $ax.globalVariableProvider.getVariableValue('dragtime') < 1000) { - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onSwipeLeft"); - } - - if($ax.globalVariableProvider.getVariableValue('totaldragx') > 30 && $ax.globalVariableProvider.getVariableValue('dragtime') < 1000) { - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onSwipeRight"); - } - - var totalDragY = $ax.globalVariableProvider.getVariableValue('totaldragy'); - if(totalDragY < -30 && $ax.globalVariableProvider.getVariableValue('dragtime') < 1000) { - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onSwipeUp"); - } - - if(totalDragY > 30 && $ax.globalVariableProvider.getVariableValue('dragtime') < 1000) { - $ax.event.raiseSyntheticEvent(widgetDragInfo.widgetId, "onSwipeDown"); - } - - if(widgetDragInfo.cursorChanged) { - window.document.body.style.cursor = widgetDragInfo.oldBodyCursor; - var widget = window.document.getElementById(widgetDragInfo.widgetId); - // It may be null if OnDragDrop filtered out the widget - if(widget != null) widget.style.cursor = widgetDragInfo.oldCursor; - //we don't seems need to reset nicescroll cursor on container, nicescroll seems updates its cursor - // if(widgetDragInfo.oldNiceScrollContainerCursor != undefined) { - // var niceScrollContainer = $ax.adaptive.getNiceScrollContainer(widget); - // if(niceScrollContainer) niceScrollContainer.style.cursor = widgetDragInfo.oldNiceScrollContainerCursor; - // widgetDragInfo.oldNiceScrollContainerCursor = undefined; - // } - widgetDragInfo.cursorChanged = undefined; - } - - if(widgetDragInfo.targetWidget == tg && !event.changedTouches) { - // suppress the click after the drag on desktop browsers - if(IE_10_AND_BELOW && widgetDragInfo.targetWidget) { - $ax.event.addEvent(widgetDragInfo.targetWidget, 'click', _suppressClickAfterDrag, true, true); - $ax.event.addEvent(widgetDragInfo.targetWidget, "onmousemove", _removeSuppressEvents, true, true); - } else { - $ax.event.addEvent(document, "click", _suppressClickAfterDrag, true); - $ax.event.addEvent(document, "mousemove", _removeSuppressEvents, true); - - } - } - } - - widgetDragInfo.hasDragged = false; - widgetDragInfo.movedWidgets = new Object(); - widgetDragInfo.started = false; - - return false; - }; - - $ax.drag.GetDragX = function() { - if(widgetDragInfo.hasDragged) return widgetDragInfo.xDelta; - return 0; - }; - - $ax.drag.GetDragY = function() { - if(widgetDragInfo.hasDragged) return widgetDragInfo.yDelta; - return 0; - }; - - $ax.drag.GetTotalDragX = function() { - if(widgetDragInfo.hasDragged) return widgetDragInfo.currentX - widgetDragInfo.cursorStartX; - return 0; - }; - - $ax.drag.GetTotalDragY = function() { - if(widgetDragInfo.hasDragged) return widgetDragInfo.currentY - widgetDragInfo.cursorStartY; - return 0; - }; - - $ax.drag.GetDragTime = function() { - if(widgetDragInfo.hasDragged) return widgetDragInfo.currentTime - widgetDragInfo.startTime; - return 600000; - }; - - $ax.drag.LogMovedWidgetForDrag = function (id, dragInfo) { - dragInfo = dragInfo || widgetDragInfo; - if(dragInfo.hasDragged) { - var containerIndex = id.indexOf('_container'); - if(containerIndex != -1) id = id.substring(0, containerIndex); - - // If state or other non-widget id, this should not be dragged, and should exit out to avoid exceptions. - if(!$obj(id)) return; - - var query = $ax('#' + id); - //var x = query.left(); - //var y = query.top(); - var viewportLocation = query.viewportLocation(); - var x = viewportLocation.left; - var y = viewportLocation.top; - - var movedWidgets = dragInfo.movedWidgets; - if(!movedWidgets[id]) { - movedWidgets[id] = new Location(x, y); - } - } - }; - - var Location = function(x, y) { - this.x = x; - this.y = y; - }; - $ax.drag.location = Location; - - var Rectangle = $ax.drag.Rectangle = function(x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.right = x + width; - this.bottom = y + height; - }; - - Rectangle.prototype.IntersectsWith = function(rect) { - if(this.Invalid()) return false; - if(rect.length) { - for(var i = 0; i < rect.length; i++) if(!rect[i].Invalid && this.IntersectsWith(rect[i])) return true; - return false; - } - if(rect.Invalid()) return false; - return this.x < rect.right && this.right > rect.x && this.y < rect.bottom && this.bottom > rect.y; - }; - - Rectangle.prototype.Invalid = function() { - return this.x == -1 && this.y == -1 && this.width == -1 && this.height == -1; - }; - - Rectangle.prototype.Move = function(x, y) { - return new Rectangle(x, y, this.width, this.height); - }; -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/events.js b/web/main/static/resources/scripts/axure/events.js deleted file mode 100644 index eade1fa..0000000 --- a/web/main/static/resources/scripts/axure/events.js +++ /dev/null @@ -1,1996 +0,0 @@ -// ******* Features MANAGER ******** // - -$axure.internal(function($ax) { - var _features = $ax.features = {}; - var _supports = _features.supports = {}; - - // Got this from http://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser - let isMobile = navigator.userAgent.match(/Android/i) - || navigator.userAgent.match(/webOS/i) - || navigator.userAgent.match(/iPhone/i) - || navigator.userAgent.match(/iPad/i) - || navigator.userAgent.match(/iPod/i) - || navigator.userAgent.match(/BlackBerry/i) - || navigator.userAgent.match(/Tablet PC/i) - || navigator.userAgent.match(/Windows Phone/i); - - if(isMobile || navigator.maxTouchPoints || navigator.msMaxTouchPoints) { - _supports.touchstart = typeof window.ontouchstart !== 'undefined'; - _supports.touchmove = typeof window.ontouchmove !== 'undefined'; - _supports.touchend = typeof window.ontouchend !== 'undefined'; - - _supports.pointerdown = typeof window.onpointerdown !== 'undefined'; - _supports.pointerup = typeof window.onpointerup !== 'undefined'; - _supports.pointermove = typeof window.onpointermove !== 'undefined'; - } - - _supports.mobile = _supports.touchstart && _supports.touchend && _supports.touchmove; - // || _supports.pointerdown && _supports.pointerup && _supports.pointermove; - _supports.windowsMobile = navigator.userAgent.match(/Tablet PC/i) || navigator.userAgent.match(/Windows Phone/i); - - var _eventNames = _features.eventNames = {}; - _eventNames.mouseDownName = _supports.touchstart ? 'touchstart' : _supports.pointerdown ? 'pointerdown' : 'mousedown'; - _eventNames.mouseUpName = _supports.touchend ? 'touchend' : _supports.pointerup ? 'pointerup' : 'mouseup'; - _eventNames.mouseMoveName = _supports.touchmove ? 'touchmove' : _supports.pointermove ? 'pointermove' : 'mousemove'; -}); - -// ******* EVENT MANAGER ******** // -$axure.internal(function ($ax) { - var isConsoleTracing = false - var isPageLoading = true; - var savedMessages = []; - - // Every time Debug begins/ends tracing or a new Debug.js file finishes loading this value will be updated - $axure.messageCenter.addStateListener("isTracing", function (key, value) { - isConsoleTracing = value; - isPageLoading = false; - - if (isConsoleTracing) { - for (var i = 0; i < savedMessages.length; i++) { - $ax.messageCenter.postMessage(savedMessages[i]["message"], savedMessages[i]["data"]); - } - } - - savedMessages = []; - }); - - var postMessage = function (message, data) { - // While page is still loading, we do not know if Console is set to trace, so save messages until load is finished and trace status can be determined - if (isPageLoading) { - savedMessages.push({ 'message': message, 'data': data }); - } else if (isConsoleTracing) { - $ax.messageCenter.postMessage(message, data); - } - } - - var _objectIdToEventHandlers = {}; - - var _jBrowserEvent = undefined; - $ax.setjBrowserEvent = function(event) { - _jBrowserEvent = event; - }; - - $ax.getjBrowserEvent = function() { - return _jBrowserEvent; - }; - - var _event = {}; - $ax.event = _event; - - //initilize state - _event.mouseOverObjectId = ''; - _event.mouseDownObjectId = ''; - _event.mouseOverIds = []; - - var EVENT_NAMES = ['mouseenter', 'mouseleave', 'contextmenu', 'change', 'focus', 'blur']; - - - // Tap, double tap, and touch move, or synthetic. - if(!$ax.features.supports.mobile) { - EVENT_NAMES[EVENT_NAMES.length] = 'click'; - EVENT_NAMES[EVENT_NAMES.length] = 'dblclick'; - EVENT_NAMES[EVENT_NAMES.length] = 'mousemove'; - } - - // add the event names for the touch events - EVENT_NAMES[EVENT_NAMES.length] = $ax.features.eventNames.mouseDownName; - EVENT_NAMES[EVENT_NAMES.length] = $ax.features.eventNames.mouseUpName; - - for(var i = 0; i < EVENT_NAMES.length; i++) { - var eventName = EVENT_NAMES[i]; - //we need the function here to circumvent closure modifying eventName - _event[eventName] = (function(event_Name) { - return function(elementId, fn) { - var elementIdQuery = $jobj(elementId); - var type = $ax.getTypeFromElementId(elementId); - - //we need specially track link events so we can enable and disable them along with - //their parent widgets - if(elementIdQuery.is('a')) _attachCustomObjectEvent(elementId, event_Name, fn); - //see notes below - else if($ax.IsTreeNodeObject(type)) _attachTreeNodeEvent(elementId, event_Name, fn); - else if ($ax.IsImageFocusable(type) && (event_Name == 'focus' || event_Name == 'blur')) { - var suitableChild; - var imgChild = $ax.repeater.applySuffixToElementId(elementId, '_img'); - var divChild = $ax.repeater.applySuffixToElementId(elementId, '_div'); - - for (var j = 0; j < elementIdQuery[0].children.length; j++) { - if (elementIdQuery[0].children[j].id == imgChild) suitableChild = imgChild; - if (!suitableChild && elementIdQuery[0].children[j].id == divChild) suitableChild = divChild; - } - if(!suitableChild) suitableChild = imgChild; - _attachDefaultObjectEvent($jobj(suitableChild), elementId, event_Name, fn); - } else { - var inputId = $ax.INPUT(elementId); - var isInput = $jobj(inputId).length != 0; - var id = isInput && (event_Name == 'focus' || event_Name == 'blur') ? inputId : elementId; - _attachDefaultObjectEvent($jobj(id), elementId, event_Name, fn); - } - }; - })(eventName); - } - - var AXURE_TO_JQUERY_EVENT_NAMES = { - 'onMouseOver': 'mouseenter', - 'onMouseOut': 'mouseleave', - 'onContextMenu': 'contextmenu', - 'onChange': 'change', - 'onFocus': 'focus', - 'onLostFocus': 'blur' - }; - - // Tap, double tap, and touch move, or synthetic. - if(!$ax.features.supports.mobile) { - AXURE_TO_JQUERY_EVENT_NAMES.onClick = 'click'; - AXURE_TO_JQUERY_EVENT_NAMES.onDoubleClick = 'dblclick'; - AXURE_TO_JQUERY_EVENT_NAMES.onMouseMove = 'mousemove'; - } - - AXURE_TO_JQUERY_EVENT_NAMES.onMouseDown = $ax.features.eventNames.mouseDownName; - AXURE_TO_JQUERY_EVENT_NAMES.onMouseUp = $ax.features.eventNames.mouseUpName; - //for dp, if mouse entered without leaving, don't fire mouse enter again - var mouseEnterGuard = {}; - var _attachEvents = function (diagramObject, elementId, doMouseEnterGuard) { - - var inputId = $ax.repeater.applySuffixToElementId(elementId, '_input'); - var id = $jobj(inputId).length ? inputId : elementId; - - for(var eventName in diagramObject.interactionMap) { - var jQueryEventName = AXURE_TO_JQUERY_EVENT_NAMES[eventName]; - if(!jQueryEventName) continue; - - _event[jQueryEventName](id, - //this is needed to escape closure - (function(axEventObject) { - return function (e) { - if(e.type == 'mouseenter' && doMouseEnterGuard) { - if(mouseEnterGuard[elementId]) return; - else mouseEnterGuard[elementId] = true; - } - - $ax.setjBrowserEvent(e); - // console.log(axEventObject.description); - var eventInfo = $ax.getEventInfoFromEvent($ax.getjBrowserEvent(), false, elementId); - _handleEvent(elementId, eventInfo, axEventObject); - }; - })(diagramObject.interactionMap[eventName]) - ); - - if(jQueryEventName.toLowerCase() == 'mouseenter' && doMouseEnterGuard) { - $jobj(elementId).on('mouseleave touchend', function() { - mouseEnterGuard[elementId] = false; - }); - } - } - - }; - - var _eventTypeToKey = { 'OnFocus': 'onFocus', 'OnLostFocus': 'onLostFocus' }; - var _createProxies = function(diagramObject, elementId) { - var createFocus = _needsProxy(diagramObject, elementId, 'onFocus'); - var createLostFocus = _needsProxy(diagramObject, elementId, 'onLostFocus'); - - if(!createFocus && !createLostFocus) return; - - if(!diagramObject.interactionMap) diagramObject.interactionMap = {}; - if(createFocus) diagramObject.interactionMap.onFocus = { proxy: true, eventType: 'OnFocus' }; - if (createLostFocus) diagramObject.interactionMap.onLostFocus = { proxy: true, eventType: 'OnLostFocus' }; - } - - var preventDefaultEvents = ['OnContextMenu', 'OnKeyUp', 'OnKeyDown', 'OnPageContextMenu', 'OnPageKeyUp', 'OnPageKeyDown']; - var allowBubble = ['OnFocus', 'OnResize', 'OnMouseOut', 'OnMouseOver']; - - var _canClick = true; - var _startScroll = []; - var _setCanClick = function(canClick) { - _canClick = canClick; - if(_canClick) _startScroll = [$(window).scrollLeft(), $(window).scrollTop()]; - }; - - var _getCanClick = function () { - if(_startScroll.length == 0) return _canClick; - var endScroll = [$(window).scrollLeft(), $(window).scrollTop()]; - return _canClick && _startScroll[0] == endScroll[0] && _startScroll[1] == endScroll[1]; - }; - - //var _notAllowedInvisible = function (type) { - // $ax.getTypeFromElementId(elementId); - - // return !$ax.public.fn.IsReferenceDiagramObject(type) && !$ax.public.fn.IsLayer(type); - //} - - - var _notAllowedInvisible = function (id) { - var type = $ax.getTypeFromElementId(id); - if ($ax.public.fn.IsReferenceDiagramObject(type) || $ax.public.fn.IsLayer(type)) return false; - return !($ax.public.fn.IsVector(type) && _hasCompoundImage(id)); - } - - var _hasCompoundImage = function (id) { - var query = $jobj(id); - return $ax.public.fn.isCompoundVectorHtml(query[0]); - } - - var _suppressedEvents = {}; // Suppressed for next occurance. - var _blockedEvents = {}; // Blocked until unblocked. - _event.addSuppressedEvent = function(id, event) { - if(!_suppressedEvents[id]) _suppressedEvents[id] = []; - var events = _suppressedEvents[id]; - if(events.indexOf(event) != -1) return; - events.push(event); - } - - _event.blockEvent = function(id, event) { - if(!_blockedEvents[id]) _blockedEvents[id] = {}; - var events = _blockedEvents[id]; - if(events[event]) ++events[event]; - else events[event] = 1; - return function() { _unblockEvent(id, event); }; - } - - var _isSuppressedEvent = function(id, event) { - var suppressedEvents = _suppressedEvents[id]; - var blockedEvents = _blockedEvents[id]; - return (suppressedEvents && suppressedEvents.indexOf(event) != -1) || (blockedEvents && blockedEvents[event]); - } - - var _removeSuppressedEvent = function(id, event) { - var events = _suppressedEvents[id]; - if(!events) return; - if(events.length == 1) { - delete _suppressedEvents[id]; - } else { - var eventIndex = events.indexOf(event); - for(var i = eventIndex + 1; i < events.length; i++) events[i - 1] = events[i]; - events.pop(); - } - } - var _unblockEvent = function(id, event) { - var events = _blockedEvents[id]; - if(events) { - if(--events[event] > 0) return; - } - _removeSuppressedEvent(id, event); - } - - var _unblockEvent = function(id, event) { - var events = _blockedEvents[id]; - if(events) { - if(--events[event] > 0) return; - } - _removeSuppressedEvent(id, event); - } - - var eventNesting = 0; - var eventNestingTime = new Date().getTime(); - - var _handleEvent = $ax.event.handleEvent = function (elementId, eventInfo, axEventObject, skipShowDescriptions, synthetic) { - var eventType = axEventObject.eventType; - if(_enteredWidgets[elementId] && eventType == 'OnMouseEnter') return; // Suppress entering a widget when already in widget (ie only) - if(_isSuppressedEvent(elementId, eventType)) { - _removeSuppressedEvent(elementId, eventType); - return; - } - - if(axEventObject.proxy) { - var firingId = _widgetToFocusParent[elementId]; - if(firingId) { - var firingObj = $obj(firingId); - var nextEventObj = firingObj.interactionMap && firingObj.interactionMap[_eventTypeToKey[eventType]]; - if(!nextEventObj) nextEventObj = axEventObject; - _handleEvent(firingId, eventInfo, nextEventObj, skipShowDescriptions, synthetic); - } - return; - } -// var x = JSON.stringify(eventInfo); -// var y = JSON.stringify(axEventObject); - - var fireTime = new Date().getTime(); - - if(fireTime - eventNestingTime > 100) { - eventNestingTime = fireTime; - eventNesting = 0; - } - - if(eventNesting === 0) { - $ax.recording.maybeRecordEvent(elementId, eventInfo, axEventObject, fireTime); - } - - eventNesting += 1; - - if (!synthetic && !_getCanClick() && (eventType == 'OnClick' || eventType == 'OnPageClick')) return; - // If you are supposed to suppress, do that right away. - if(suppressedEventStatus[eventType]) { - return; - } - - var currentEvent = $ax.getjBrowserEvent(); - if(!synthetic && currentEvent && currentEvent.originalEvent && currentEvent.originalEvent.handled && !eventInfo.isMasterEvent) return; - if(!synthetic && elementId && !$ax.style.getObjVisible(elementId) && _notAllowedInvisible(elementId)) return; - - //if debug - var axObj = $obj(elementId); - var axObjLabel = axObj ? axObj.label : eventInfo.label; - var axObjType = axObj ? axObj.friendlyType : eventInfo.friendlyType; - if (!skipShowDescriptions || eventType == 'OnPageLoad') postMessage('axEvent', { 'label': axObjLabel, 'type': axObjType, 'event': axEventObject }); - - var bubble = true; - var showCaseDescriptions = !skipShowDescriptions && _shouldShowCaseDescriptions(axEventObject); - if(!showCaseDescriptions) { - //handle case descriptions - var caseGroups = []; - var currentCaseGroup = []; - caseGroups[0] = currentCaseGroup; - - // Those refreshes not after a wait - var guaranteedRefreshes = {}; - - var caseGroupIndex = 0; - for(var i = 0; i < axEventObject.cases.length; i++) { - var currentCase = axEventObject.cases[i]; - if(currentCase.isNewIfGroup && i != 0) { - caseGroupIndex++; - currentCaseGroup = []; - caseGroups[caseGroups.length] = currentCaseGroup; - // Joon: Isn't caseGroups.length always equal to caseGroupIndex? - } - currentCaseGroup[currentCaseGroup.length] = currentCase; - - for(var j = 0; j < currentCase.actions.length; j++) { - var action = currentCase.actions[j]; - if(action.action == 'wait') break; - if(action.action != 'refreshRepeater') continue; - for(var k = 0; k < action.repeatersToRefresh.length; k++) { - var id = $ax.getElementIdsFromPath(action.repeatersToRefresh[k], eventInfo)[0]; - if(id) guaranteedRefreshes[id] = caseGroupIndex; - } - } - } - - for(var i = 0; i < caseGroups.length; i++) { - var groupRefreshes = []; - for(var key in guaranteedRefreshes) { - if(guaranteedRefreshes[key] == i) groupRefreshes[groupRefreshes.length] = key; - } - bubble = _handleCaseGroup(eventInfo, caseGroups[i], groupRefreshes) && bubble; - } - } else { - _showCaseDescriptions(elementId, eventInfo, axEventObject, synthetic); - bubble = false; - } - - // If not handled, synthetically bubble if you can - if(bubble && _widgetToFocusParent[elementId]) { - firingId = _widgetToFocusParent[elementId]; - if(firingId) { - firingObj = $obj(firingId); - nextEventObj = firingObj.interactionMap && firingObj.interactionMap[_eventTypeToKey[eventType]]; - if(!nextEventObj) nextEventObj = axEventObject; - _handleEvent(firingId, eventInfo, nextEventObj, skipShowDescriptions, synthetic); - } - return; - } - - // Only trigger a supression if it handled this event - if(!bubble && suppressingEvents[eventType]) { - suppressedEventStatus[suppressingEvents[eventType]] = true; - } - - $ax.action.flushAllResizeMoveActions(eventInfo); - - // This should not be needed anymore. All refreshes should be inserted, or handled earlier. - var repeaters = $ax.deepCopy($ax.action.repeatersToRefresh); - while($ax.action.repeatersToRefresh.length) $ax.action.repeatersToRefresh.pop(); - for(i = 0; i < repeaters.length; i++) $ax.repeater.refreshRepeater(repeaters[i], eventInfo); - - if(currentEvent && currentEvent.originalEvent) { - currentEvent.originalEvent.handled = !synthetic && !bubble && allowBubble.indexOf(eventType) == -1; - //currentEvent.originalEvent.donotdrag = currentEvent.donotdrag || (!bubble && eventDescription == 'OnMouseDown'); - - // Prevent default if necessary - if (currentEvent.originalEvent.handled && preventDefaultEvents.indexOf(eventType) != -1) { - currentEvent.preventDefault(); - } - } - - eventNesting -= 1; - - if(!showCaseDescriptions) postMessage('axEventComplete'); - - }; - - var _handleScrollEvent = function (elementId, eventInfo, originalEvent, scrolledUp, scrolledDown, interactionMap, skipShowDescription, synthetic) { - if (!interactionMap) return; - if (interactionMap.onScroll) _handleEvent(elementId, eventInfo, interactionMap.onScroll, skipShowDescription, synthetic); - - var wasHandled = originalEvent.handled; - if (interactionMap.onScrollUp && scrolledUp) { - originalEvent.handled = false; - _handleEvent(elementId, eventInfo, interactionMap.onScrollUp, skipShowDescription, synthetic); - } else if (interactionMap.onScrollDown && scrolledDown) { - originalEvent.handled = false; - _handleEvent(elementId, eventInfo, interactionMap.onScrollDown, skipShowDescription, synthetic); - } - originalEvent.handled |= wasHandled; - } - - var _showCaseDescriptions = function(elementId, eventInfo, axEventObject, synthetic) { - - if(axEventObject.cases.length == 0) return true; - - var linksId = elementId + "linkBox"; - $('#' + linksId).remove(); - - var $container = $("<div class='intcases' id='" + linksId + "'></div>"); - - if(!_isEventSimulating(axEventObject)) { - var copy = $ax.eventCopy(eventInfo); - for(var i = 0; i < axEventObject.cases.length; i++) { - var $link = $("<div class='intcaselink'>" + axEventObject.cases[i].description + "</div>"); - $link.click(function(j) { - return function () { - var currentCase = axEventObject.cases[j]; - postMessage('axCase', { 'item': currentCase.description, 'description': currentCase.conditionString, 'color': currentCase.caseColorHex }) - for(var k = 0; k < currentCase.actions.length; k++) { - var currentAction = currentCase.actions[k]; - - // Only use action's direct description if no action info descriptions exist - postMessage('axAction', { 'name': currentAction.displayName }); - //postMessage('axAction', { 'item': currentAction.description, 'description': (Object.keys(currentAction.actionInfoDescriptions).length > 0 ? "" : currentAction.description) }); - - for (var target in currentAction.actionInfoDescriptions) { - var infoDescriptions = currentAction.actionInfoDescriptions[target]; - for (var shortDescription in infoDescriptions) { - postMessage('axInfo', { 'item': target, 'description': shortDescription, 'longDescription': infoDescriptions[shortDescription] }); - } - } - } - postMessage('axEventComplete'); - - var bubble = $ax.action.dispatchAction(copy, axEventObject.cases[j].actions); - $ax.action.flushAllResizeMoveActions(copy); - $('#' + linksId).remove(); - return bubble; - }; - } (i) - ); - - $container.append($link); - } - } else { - var fullDescription = axEventObject.description + ":<br>"; - for(var i = 0; i < axEventObject.cases.length; i++) { - var currentCase = axEventObject.cases[i]; - fullDescription += " " + currentCase.description.replace(/<br>/g, '<br> ') + ":<br>"; - for(var j = 0; j < currentCase.actions.length; j++) { - fullDescription += " " + currentCase.actions[j].description.replace(/<br>/g, '<br> ') + "<br>"; - } - } - fullDescription = fullDescription.substring(0, fullDescription.length - 4); - - var $link = $("<div class='intcaselink'>" + fullDescription + "</div>"); - $link.click(function() { - _handleEvent(elementId, eventInfo, axEventObject, true, synthetic); - postMessage('axEventComplete'); - $('#' + linksId).remove(); - return; - }); - $container.append($link); - } - $container.mouseleave(function(e) { $ax.legacy.SuppressBubble(e); }); - $('body').append($container); - _showCaseLinks(eventInfo, linksId); - }; - - var _showCaseLinks = function(eventInfo, linksId) { - var links = window.document.getElementById(linksId); - - links.style.top = eventInfo.pageY; - - var left = eventInfo.pageX; - links.style.left = left; - $ax.visibility.SetVisible(links, true); - $ax.legacy.BringToFront(linksId, true); - // Switch to using jquery if this is still needed. Really old legacy code, likely for a browser no longer supported. - //$ax.legacy.RefreshScreen(); - }; - - - var _shouldShowCaseDescriptions = function(axEventObject) { - if($ax.document.configuration.linkStyle == "alwaysDisplayTargets") return true; - if($ax.document.configuration.linkStyle == "neverDisplayTargets") return false; - if(axEventObject.cases.length == 0) return false; - if(_isEventSimulating(axEventObject)) return false; - if(axEventObject.cases.length >= 2) return true; - return false; - }; - - var _isEventSimulating = function(axEventObject) { - for(var i = 0; i < axEventObject.cases.length; i++) { - if(axEventObject.cases[i].condition) return true; - } - return false; - }; - - var _handleCaseGroup = function(eventInfo, caseGroup, groupRefreshes) { - for(var i = 0; i < caseGroup.length; i++) { - var currentCase = caseGroup[i]; - if(!currentCase.condition || _processCondition(currentCase.condition, eventInfo)) { - postMessage('axCase', { 'item': currentCase.description, 'description': currentCase.conditionString, 'color': currentCase.caseColorHex }) - - for(var j = 0; j < currentCase.actions.length; j++) { - var currentAction = currentCase.actions[j]; - if (currentAction.action != 'refreshRepeater') { - // Only use action's direct description if no action info descriptions exist - postMessage('axAction', { 'name': currentAction.displayName }); - //postMessage('axAction', { 'item': currentAction.description, 'description': (Object.keys(currentAction.actionInfoDescriptions).length > 0 ? "" : currentAction.description) }); - - for (var target in currentAction.actionInfoDescriptions) { - var infoDescriptions = currentAction.actionInfoDescriptions[target]; - for (var shortDescription in infoDescriptions) { - postMessage('axInfo', { 'item': target, 'description': shortDescription, 'longDescription': infoDescriptions[shortDescription] }); - } - } - } - } - - for(var j = 0; j < currentCase.actions.length; j++) { - var action = currentCase.actions[j]; - if(action.action == 'wait') break; - if(action.action != 'refreshRepeater') continue; - for(var k = 0; k < action.repeatersToRefresh.length; k++) { - var id = $ax.getElementIdsFromPath(action.repeatersToRefresh[i], eventInfo)[i]; - if(id) { - var index = groupRefreshes.indexOf(id); - if(index != -1) $ax.splice(groupRefreshes, index); - } - } - } - - // Any guaranteed refreshes that aren't accounted for must be run still. - $ax.action.tryRefreshRepeaters(groupRefreshes, eventInfo); - - $ax.action.dispatchAction(eventInfo, currentCase.actions); - return false; - } - } - - // Any guaranteed refreshes that aren't accounted for must be run still. - $ax.action.tryRefreshRepeaters(groupRefreshes, eventInfo); - return true; - }; - - var _processCondition = function(expr, eventInfo) { - return $ax.expr.evaluateExpr(expr, eventInfo); - }; - - var _attachTreeNodeEvent = function(elementId, eventName, fn) { - //we need to set the cursor here because we want to make sure that every tree node has the default - //cursor set and then it's overridden if it has a click - if(eventName == 'click') window.document.getElementById(elementId).style.cursor = 'pointer'; - - _attachCustomObjectEvent(elementId, eventName, fn); - }; - - var _attachDefaultObjectEvent = function(elementIdQuery, elementId, eventName, fn) { - var func = function(e) { - if($ax.style.IsWidgetDisabled(elementId) || _shouldIgnoreLabelClickFromCheckboxOrRadioButton(e)) return true; - return fn.apply(this, arguments); - }; - - var bind = !elementIdQuery[eventName]; - if(bind) elementIdQuery.bind(eventName, func); - else elementIdQuery[eventName](func); - }; - - var _shouldIgnoreLabelClickFromCheckboxOrRadioButton = function (e) { - return (((_hasParentWithMatchingSelector(e.target, '.checkbox') && $(e.target).closest('label').length != 0) || - _hasParentWithMatchingSelector(e.target, '.radio_button') && $(e.target).closest('label').length != 0)) && e.type == 'click'; - }; - - var _hasParentWithMatchingSelector = function (target, selector) { - return $(target).parents(selector).length != 0; - }; - - var _attachCustomObjectEvent = function(elementId, eventName, fn) { - var handlers = _objectIdToEventHandlers[elementId]; - if(!handlers) _objectIdToEventHandlers[elementId] = handlers = {}; - - var fnList = handlers[eventName]; - if(!fnList) handlers[eventName] = fnList = []; - - fnList[fnList.length] = fn; - }; - - var _fireObjectEvent = function(elementId, event, originalArgs) { - var element = window.document.getElementById(elementId); - - var handlerList = _objectIdToEventHandlers[elementId] && _objectIdToEventHandlers[elementId][event]; - if(handlerList) { - for(var i = 0; i < handlerList.length; i++) handlerList[i].apply(element, originalArgs); - } - - eventNesting -= 1; - - }; - - var _layerToFocusableWidget = {}; - var _widgetToFocusParent = {}; - _event.layerMapFocus = function(layer, elementId) { - var mainObj = layer.objs[0]; - // If first child non existant return - if (!mainObj) return; - - var mainId = $ax.getElementIdFromPath([mainObj.id], { relativeTo: elementId }); - _widgetToFocusParent[mainId] = elementId; - - // If first child is a layer, call recursively - if ($ax.public.fn.IsLayer(mainObj.type)) { - _event.layerMapFocus(mainObj, mainId); - var baseId = _layerToFocusableWidget[mainId]; - if(baseId) _layerToFocusableWidget[elementId] = baseId; - return; - } - - _layerToFocusableWidget[elementId] = mainId; - } - - var _needsProxy = function(obj, id, proxyName) { - // layers don't need on focus ever, proxies will handle them - if ($ax.public.fn.IsLayer(obj.type)) return false; - // If you already focus you don't need to force yourself to proxy. - if(obj.interactionMap && obj.interactionMap[proxyName]) return false; - - var parentId = _widgetToFocusParent[id]; - if(parentId) return _needsProxyHelper(parentId, proxyName); - return false; - } - - var _needsProxyHelper = function(id, proxyName) { - var obj = $obj(id); - if(obj.interactionMap && obj.interactionMap[proxyName]) return true; - - var parentId = _widgetToFocusParent[id]; - if(parentId) return _needsProxyHelper(parentId, proxyName); - return false; - } - - //for button shapes and images the img is focusable instead of the div to get better outlines - // For layers, we remember who their proxy is. - $ax.event.getFocusableWidgetOrChildId = function (elementId) { - var mappedId = _layerToFocusableWidget[elementId]; - if (mappedId) elementId = mappedId; - - var inputId = $ax.repeater.applySuffixToElementId(elementId, '_input'); - var inputQuery = $jobj(inputId); - if(inputQuery.length > 0) return inputId; - - var imgId = $ax.repeater.applySuffixToElementId(elementId, '_img'); - var imgQuery = $jobj(imgId); - if (imgQuery.length > 0) return imgId; - - var divId = $ax.repeater.applySuffixToElementId(elementId, '_div'); - var divQuery = $jobj(divId); - if (divQuery.length > 0) return divId; - - return elementId; - }; - - var _enteredWidgets = {}; - - // key is the suppressing event, and the value is the event that is supressed - var suppressingEvents = {}; - // key is the event that will cancel the suppression, and value is the event that was being suppressed - var cancelSuppressions = {}; - // suppressed event maps to true if it is supressed - var suppressedEventStatus = {}; - - var initSuppressingEvents = function () { - suppressingEvents['OnLongClick'] = 'OnClick'; - cancelSuppressions['onMouseDown'] = 'OnClick'; - - // Have to cancel suppressed event here. Only works for non-synthetic events currently - for(var key in cancelSuppressions) { - var jEventName = AXURE_TO_JQUERY_EVENT_NAMES[key]; - if(!jEventName) continue; - $('body').bind(jEventName, function () { - suppressedEventStatus[cancelSuppressions[key]] = false; - }); - } - }; - - // TODO: It may be a good idea to split this into multiple functions, or at least pull out more similar functions into private methods - var _initializeObjectEvents = function(query, refreshType) { - var skipSelectedIds = new Set(); - query.each(function (dObj, elementId) { - if (dObj == null) return; // TODO: Update expo items that pass here to potentially remove this logic - var $element = $jobj(elementId); - var itemId = $ax.repeater.getItemIdFromElementId(elementId); - - // Focus has to be done before on focus fires - // Set up focus - if ($ax.public.fn.IsTextArea(dObj.type) || $ax.public.fn.IsTextBox(dObj.type) || $ax.public.fn.IsCheckBox(dObj.type) || $ax.public.fn.IsRadioButton(dObj.type) || - $ax.public.fn.IsListBox(dObj.type) || $ax.public.fn.IsComboBox(dObj.type) || $ax.public.fn.IsButton(dObj.type) || - (dObj.tabbable && ($ax.public.fn.IsImageBox(dObj.type) || $ax.public.fn.IsVector(dObj.type) || $ax.IsTreeNodeObject(dObj.type) || $ax.public.fn.IsTableCell(dObj.type)))) { - var focusObj = $jobj($ax.event.getFocusableWidgetOrChildId(elementId)); - focusObj.focus(function() { - window.lastFocusedControl = elementId; - $ax.style.SetWidgetFocused(elementId, true); - }); - focusObj.blur(function() { - $ax.style.SetWidgetFocused(elementId, false); - }); - } - // [MAS: Supressing events were here] - _createProxies(dObj, elementId); - var isDynamicPanel = $ax.public.fn.IsDynamicPanel(dObj.type); - if(dObj.interactionMap) { - _attachEvents(dObj, elementId, isDynamicPanel); - }; - - - - if (IE || $axure.browser.isEdge) { - $element.mouseenter(function() { - _enteredWidgets[elementId] = true; - }).mouseleave(function() { - _enteredWidgets[elementId] = false; - }); - } - - _attachIxStyleEvents(dObj, elementId, $element); - - var $axElement = $ax('#' + elementId); - // Base case is set up selected disabled based on the default in the axobj, for non, repeaters and resetting repeaters - var itemReset = refreshType == $ax.repeater.refreshType.reset; - if(!itemId || itemReset) { - //initialize disabled elements, do this first before selected, cause if a widget is disabled, we don't want to apply selected style anymore - if ($ax.public.fn.IsVector(dObj.type) || $ax.public.fn.IsImageBox(dObj.type) || isDynamicPanel || $ax.public.fn.IsLayer(dObj.type) - || $ax.public.fn.IsTextBox(dObj.type) || $ax.public.fn.IsTextArea(dObj.type) || $ax.public.fn.IsComboBox(dObj.type) || $ax.public.fn.IsListBox(dObj.type) - || $ax.public.fn.IsCheckBox(dObj.type) || $ax.public.fn.IsRadioButton(dObj.type)) { - - if (dObj.disabled) $axElement.enabled(false); - - // Initialize selected elements - // only set one member of selection group selected since subsequent calls - // will unselect the previous one anyway - if(dObj.selected && !skipSelectedIds.has(elementId)) { - var group = $('#' + elementId).attr('selectiongroup'); - if(group) for(var item of $("[selectiongroup='" + group + "']")) skipSelectedIds.add(item.id); - $axElement.selected(true); - } - } - } else if(refreshType == $ax.repeater.refreshType.preEval) { - // Otherwise everything should be set up correctly by pre-eval, want to set up selected disabled dictionaries (and disabled status) - // Disabled layer/dynamic panel don't have the disabled class, but they do have the disabled attr written out, so use that in that case - if ($element.hasClass('disabled') || - (($ax.IsLayer(dObj.type) || $ax.IsDynamicPanel(dObj.type)) && $element.attr('disabled'))) $axElement.enabled(false); - if($element.hasClass('selected')) $axElement.selected(true); - } else { - // Persist means we want to leave it as is, but we want to make sure we use selected based off of the backing data, and not some class that exists because of the reset - $element.removeClass('selected'); - } - - //if(OS_MAC && WEBKIT) { - // if ($ax.public.fn.IsComboBox(dObj.type) && dObj.disabled) { - // $jobj($ax.INPUT(elementId)).css('color', 'grayText'); - // } - //}; - const isInput = $ax.public.fn.IsTextArea(dObj.type) || $ax.public.fn.IsTextBox(dObj.type); - if(isInput) { - var inputJobj = $jobj($ax.INPUT(elementId)); - inputJobj.bind('keyup', function(e) { - //prevents triggering player shortcuts - e.preventDefault(); - }); - } - - const isDateTimeTypeInput = function($input) { - const type = $input.attr('type'); - return type == 'date' || type == 'month' || type == 'time'; - } - - // Initialize Placeholders. Right now this is text boxes and text areas. - // Also, the assuption is being made that these widgets with the placeholder, have no other styles (this may change...) - var hasPlaceholder = dObj.placeholderText == '' ? true : Boolean(dObj.placeholderText); - if(isInput && hasPlaceholder) { - // This is needed to initialize the placeholder state - inputJobj.bind('focus', function () { - if(dObj.HideHintOnFocused) { - var id = this.id; - var inputIndex = id.indexOf('_input'); - if (inputIndex == -1) return; - var inputId = id.substring(0, inputIndex); - - if (!$ax.placeholderManager.isActive(inputId)) return; - $ax.placeholderManager.updatePlaceholder(inputId, false, true); - } - $ax.placeholderManager.moveCaret(this.id); - }).bind('mouseup', function() { - $ax.placeholderManager.moveCaret(this.id); - }).bind('blur', function() { - var id = this.id; - var inputIndex = id.indexOf('_input'); - if(inputIndex == -1) return; - var inputId = id.substring(0, inputIndex); - - if($jobj(id).val()) return; - $ax.placeholderManager.updatePlaceholder(inputId, true); - }); - - inputJobj.bind('input', function() { - if(!dObj.HideHintOnFocused) { //hide on type - var id = this.id; - var inputIndex = id.indexOf('_input'); - if(inputIndex == -1) return; - var inputId = id.substring(0, inputIndex); - - var $input = $jobj(id); - var emptyInputValue = !$input.val(); - - var invalidDateTimeInput = isDateTimeTypeInput($input) && !$input[0].validity.valid; - if ($ax.placeholderManager.isActive(inputId)) { - // clear text if emptyInputValue is true; - $ax.placeholderManager.updatePlaceholder(inputId, false, emptyInputValue); - } - else if (emptyInputValue && !invalidDateTimeInput) { - $ax.placeholderManager.updatePlaceholder(inputId, true); - $ax.placeholderManager.moveCaret(id, 0); - } - } - }); - - if(!ANDROID) { - inputJobj.bind('keydown', function() { - if(!dObj.HideHintOnFocused) { - var id = this.id; - var inputIndex = id.indexOf('_input'); - if(inputIndex == -1) return; - var inputId = id.substring(0, inputIndex); - - if(!$ax.placeholderManager.isActive(inputId)) return; - $ax.placeholderManager.updatePlaceholder(inputId, false, true); - } - }); - } - - $ax.placeholderManager.registerPlaceholder(elementId, dObj.placeholderText, inputJobj.attr('type') == 'password'); - $ax.placeholderManager.updatePlaceholder(elementId, !($jobj($ax.repeater.applySuffixToElementId(elementId, '_input')).val())); - } - - // Initialize assigned submit buttons - if(dObj.submitButton) { - $element.keyup(function(e) { - if(e.keyCode == '13') { - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - var path = $ax.deepCopy(dObj.submitButton.path); - path[path.length] = dObj.submitButton.id; - var itemNum = $ax.repeater.getItemIdFromElementId(elementId); - var submitId = $ax.getScriptIdFromPath(path, scriptId); - - if(itemNum && $ax.getParentRepeaterFromScriptId(submitId) == $ax.getParentRepeaterFromScriptId(scriptId)) { - submitId = $ax.repeater.createElementId(submitId, itemNum); - } - var inputId = $ax.INPUT(submitId); - if($jobj(inputId).length) submitId = inputId; - - $ax.setjBrowserEvent(e); - $ax.event.fireClick(submitId); - } - }).keydown(function(e) { - if(e.keyCode == '13') { - e.preventDefault(); - } - }); - } - - // Don't drag after mousing down on a plain text object - if ($ax.public.fn.IsTextArea(dObj.type) || $ax.public.fn.IsTextBox(dObj.type) || $ax.public.fn.IsListBox(dObj.type) || - $ax.public.fn.IsComboBox(dObj.type) || $ax.public.fn.IsCheckBox(dObj.type) || $ax.public.fn.IsRadioButton(dObj.type)) { - $element.bind($ax.features.eventNames.mouseDownName, function(event) { - event.originalEvent.donotdrag = true; - }); - } - - $element.bind($ax.features.eventNames.mouseDownName, function() { _setCanClick(true); }); - if (isDynamicPanel) { - $element.children().scroll(function () { _setCanClick(false); }); - } - - //initialize tree node cursors to default so they will override their parent - if ($ax.public.fn.IsTreeNodeObject(dObj.type) && !(dObj.interactionMap && dObj.interactionMap.onClick)) { - $element.css('cursor', 'default'); - } - - //initialize widgets that are clickable to have the pointer over them when hovering - if($ax.event.HasClick(dObj)) { - if($element) $element.css('cursor', 'pointer'); - } - - // TODO: not sure if we need this. It appears to be working without - //initialize panels for DynamicPanels - if (isDynamicPanel) { - $element.children().each(function() { - var parts = this.id.split('_'); - var state = parts[parts.length - 1].substring(5); - if(state != 0) $ax.visibility.SetVisible(this, false); - }); - } - - //initialize TreeNodes - if ($ax.public.fn.IsTreeNodeObject(dObj.type)) { - if($element.hasClass('treeroot')) return; - - var childrenId = elementId + '_children'; - var children = $element.children('[id="' + childrenId + '"]:first'); - if(children.length > 0) { - var plusMinusId = 'u' + (parseInt($ax.repeater.getScriptIdFromElementId(elementId).substring(1)) + 1); - if(itemId) plusMinusId = $ax.repeater.createElementId(plusMinusId, itemId); - if(!$jobj(plusMinusId).children().first().is('img')) plusMinusId = ''; - $ax.tree.InitializeTreeNode(elementId, plusMinusId, childrenId); - } - $element.click(function() { $ax.tree.SelectTreeNode(elementId, true); }); - } - - //initialize submenus - if ($ax.public.fn.IsMenuObject(dObj.type)) { - if($element.hasClass('sub_menu')) { - var tableCellElementId = $ax.getElementIdFromPath([dObj.parentCellId], { relativeTo: elementId }); - $ax.menu.InitializeSubmenu(elementId, tableCellElementId); - } - } - - // Attach handles for dynamic panels that propagate styles to inner items. - if ((isDynamicPanel || $ax.public.fn.IsLayer(dObj.type)) && dObj.propagate) { - $element.mouseenter(function() { - dynamicPanelMouseOver(this.id); - }).mouseleave(function() { - dynamicPanelMouseLeave(this.id); - }).bind($ax.features.eventNames.mouseDownName, function() { - dynamicPanelMouseDown(this.id); - }).bind($ax.features.eventNames.mouseUpName, function() { - dynamicPanelMouseUp(this.id); - }); - } - - // These are the dynamic panel functions for propagating rollover styles and mouse down styles to inner objects - var dynamicPanelMouseOver = function(elementId, fromChild) { - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent) { - dynamicPanelMouseOver(parent.id, true); - if(parent.direct) return; - } - if($.inArray(elementId, _event.mouseOverIds) != -1) return; - // If this event is coming from a child, don't mark that it's actually entered. - // Only mark that this has been entered if this event has naturally been triggered. (For reason see mouseleave) - if(!fromChild) _event.mouseOverIds[_event.mouseOverIds.length] = elementId; - if(elementId == _event.mouseOverObjectId) return; - _event.mouseOverObjectId = elementId; - $ax.dynamicPanelManager.propagateMouseOver(elementId, true); - }; - var dynamicPanelMouseLeave = function(elementId, fromChild) { - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent) { - dynamicPanelMouseLeave(parent.id, true); - if(parent.direct) return; - } - var index = $.inArray(elementId, _event.mouseOverIds); - // If index != -1, this has been natuarally entered. If naturally entered, then leaving child should not trigger leaving, - // but instead wait for natural mouse leave. If natural mouse enter never triggered, natural mouse leave won't so do this now. - if((index != -1) && fromChild) return; - $ax.splice(_event.mouseOverIds, index, 1); - - if(elementId == _event.mouseOverObjectId) { - _event.mouseOverObjectId = ''; - } - $ax.dynamicPanelManager.propagateMouseOver(elementId, false); - }; - - //attach handlers for button shape and tree node mouse over styles - // TODO: Can this really be removed? Trees seem to work with out (the generic hover case works for it). - // query.filter(function(obj) { - // return $ax.public.fn.IsVector(obj.type) && $ax.public.fn.IsTreeNodeObject(obj.parent.type) && - // obj.parent.style && obj.parent.style.stateStyles && - // obj.parent.style.stateStyles.mouseOver; - // }).mouseenter(function() { - // $ax.style.SetWidgetHover(this.id, true); - // }).mouseleave(function() { - // $ax.style.SetWidgetHover(this.id, false); - // }); - - //handle treeNodeObject events and prevent them from bubbling up. this is necessary because otherwise - //both a sub menu and it's parent would get a click - if ($ax.public.fn.IsTreeNodeObject(dObj.type)) { - $element.click(function() { - //todo -- this was bubbling, but then selecting a child tree node would bubble and select the parent (don't know if there is a better way) - _fireObjectEvent(this.id, 'click', arguments); - return false; - }).each(function() { - if(!this.style.cursor) { - this.style.cursor = 'default'; - } - }); - } - - // Synthetic events - - var map = dObj.interactionMap; - // Attach synthetic drag and swipe events - if(map && (map.onDragStart || map.onDrag || map.onDragDrop || map.onSwipeLeft || map.onSwipeRight || map.onSwipeUp || map.onSwipeDown)) { - if(isDynamicPanel) { - var diagrams = dObj.diagrams; - for(var i = 0; i < diagrams.length; i++) { - var panelId = $ax.repeater.applySuffixToElementId(elementId, '_state' + i); - var panel = document.getElementById(panelId); - panel.addEventListener($ax.features.eventNames.mouseDownName, function (e) { - $ax.drag.StartDragWidget(e, elementId); - }); - } - } else { - $element.bind($ax.features.eventNames.mouseDownName, - function (e) { - $ax.drag.StartDragWidget(e.originalEvent, elementId); - // if (!e.originalEvent.donotdrag) $ax.registerTouchCount(e); - // $ax.drag.StartDragWidget(e.originalEvent, elementId); - }); - } - } - - // Attach dynamic panel synthetic scroll event - if (isDynamicPanel && map && (map.onScroll || map.onScrollUp || map.onScrollDown)) { - var diagrams = dObj.diagrams; - for(var i = 0; i < diagrams.length; i++) { - var panelId = $ax.repeater.applySuffixToElementId(elementId, '_state' + i); - (function(id) { - if ($('#' + id).data('lastScrollTop') == undefined) $('#' + id).data('lastScrollTop', '0'); - _attachDefaultObjectEvent($('#' + id), elementId, 'scroll', function(e) { - $ax.setjBrowserEvent(e); - var currentEvent = $ax.getjBrowserEvent(); - var eventInfoFromEvent = $ax.getEventInfoFromEvent(currentEvent, false, elementId); - - var currentTop = $('#' + id).scrollTop(); - var lastTop = $('#' + id).data('lastScrollTop'); - - _handleScrollEvent(elementId, eventInfoFromEvent, currentEvent.originalEvent, currentTop < lastTop, currentTop > lastTop, map); - $('#' + id).data('lastScrollTop', currentTop); - }); - })(panelId); - } - } - - // Attach synthetic hover event - if (map && map.onMouseHover) { - var MIN_HOVER_HOLD_TIME = 1000; - - // So when the timeout fires, you know whether it is the same mouseenter that is active or not. - var hoverMouseCount = 0; - // Update eventInfo regularly, so position is accurate. - var hoverEventInfo; - - $element.mouseenter(function(e) { - $ax.setjBrowserEvent(e); - hoverEventInfo = $ax.getEventInfoFromEvent($ax.getjBrowserEvent(), false, elementId); - (function(currCount) { - window.setTimeout(function() { - if(currCount == hoverMouseCount) _raiseSyntheticEvent(elementId, 'onMouseHover', false, hoverEventInfo, true); - }, MIN_HOVER_HOLD_TIME); - })(hoverMouseCount); - }).mouseleave(function(e) { - $ax.setjBrowserEvent(e); - hoverMouseCount++; - }).mousemove(function(e) { - $ax.setjBrowserEvent(e); - hoverEventInfo = $ax.getEventInfoFromEvent($ax.getjBrowserEvent(), false, elementId); - }); - } - - // Attach synthetic tap and hold event. - if (map && map.onLongClick) { - var MIN_LONG_CLICK_HOLD_TIME = 750; - - // So when the timeout fires, you know whether it is the same mousedown that is active or not. - var longClickMouseCount = 0; - - $element.bind($ax.features.eventNames.mouseDownName, function(e) { - (function(currCount) { - $ax.setjBrowserEvent(e); - var eventInfo = $ax.getEventInfoFromEvent($ax.getjBrowserEvent(), false, elementId); - window.setTimeout(function() { - if(currCount == longClickMouseCount) _raiseSyntheticEvent(elementId, 'onLongClick', false, eventInfo, true); - }, MIN_LONG_CLICK_HOLD_TIME); - if(e.preventDefault) e.preventDefault(); - })(longClickMouseCount); - }).bind($ax.features.eventNames.mouseUpName, function(e) { - $ax.setjBrowserEvent(e); - longClickMouseCount++; - }); - }; - - - // Attach synthetic onSelectionChange event to droplist and listbox elements - if ($ax.event.HasSelectionChanged(dObj)) { - $element.bind('change', function(e) { - $ax.setjBrowserEvent(e); - _raiseSyntheticEvent(elementId, 'onSelectionChange'); - }); - }; - - // Highjack key up and key down to keep track of state of keyboard. - if($ax.event.HasKeyUpOrDown(dObj)) _event.initKeyEvents($element); - - // Attach synthetic onTextChange event to textbox and textarea elements - if ($ax.event.HasTextChanged(dObj)) { - var element = $jobj($ax.INPUT(elementId)); - $ax.updateElementText(elementId, element.val()); - //Key down needed because when holding a key down, key up only fires once, but keydown fires repeatedly. - //Key up because last mouse down will only show the state before the last character. - element.bind('keydown', function(e) { - $ax.setjBrowserEvent(e); - $ax.event.TryFireTextChanged(elementId); - }).bind('keyup', function(e) { - $ax.setjBrowserEvent(e); - $ax.event.TryFireTextChanged(elementId); - }); - }; - - // Attach synthetic onCheckedChange event to radiobutton and checkbox elements - if ($ax.public.fn.IsCheckBox(dObj.type) || $ax.public.fn.IsRadioButton(dObj.type)) { - var input = $jobj($ax.INPUT(elementId)); - if($ax.public.fn.IsRadioButton(dObj.type)) { - var radioGroupName = input.attr('name'); - if(input.prop('selected')) { - $ax.updateRadioButtonSelected(radioGroupName, elementId); - } - var onClick = function(e) { - if(radioGroupName !== elementId) { - var radioGroup = $("input[name='" + radioGroupName + "']").parent(); - for(var i = 0; i < radioGroup.length; i++) { - $ax.style.SetWidgetSelected(radioGroup[i].id, false, true); - } - } - $ax.style.SetWidgetSelected(elementId, true, true); - if(!$ax.style.IsWidgetDisabled(elementId)) e.originalEvent.handled = true; - }; - } else { - onClick = function(e) { - $ax.style.SetWidgetSelected(elementId, !$ax.style.IsWidgetSelected(elementId), true); - if(!$ax.style.IsWidgetDisabled(elementId)) e.originalEvent.handled = true; - }; - } - input.click(onClick); - - //$element.bind('change', function(e) { - // $ax.setjBrowserEvent(e); - // var eTarget = e.target || e.srcElement; - // _tryFireCheckedChanged(elementId, eTarget.selected); - //}); - }; - - var hasTap = map && (map.onClick || map.onDoubleClick); - var hasMove = map && map.onMouseMove; - _event.initMobileEvents(hasTap ? $element : $(), - hasMove ? $element : $(), elementId); - - - //attach link alternate styles - if(dObj.type == 'hyperlink') { - $element.mouseenter(function() { - var linkId = this.id; - if(_event.mouseOverIds.indexOf(linkId) != -1) return true; - _event.mouseOverIds[_event.mouseOverIds.length] = linkId; - var mouseOverObjectId = _event.mouseOverObjectId; - if(mouseOverObjectId && $ax.style.IsWidgetDisabled(mouseOverObjectId)) return true; - - $ax.style.SetLinkHover(linkId); - - var bubble = _fireObjectEvent(linkId, 'mouseenter', arguments); - - $ax.annotation.updateLinkLocations($ax.GetParentIdFromLink(linkId)); - return bubble; - }).mouseleave(function() { - var linkId = this.id; - $ax.splice(_event.mouseOverIds, _event.mouseOverIds.indexOf(linkId), 1); - var mouseOverObjectId = _event.mouseOverObjectId; - if(mouseOverObjectId && $ax.style.IsWidgetDisabled(mouseOverObjectId)) return true; - - $ax.style.SetLinkNotHover(linkId); - - var bubble = _fireObjectEvent(linkId, 'mouseleave', arguments); - - $ax.annotation.updateLinkLocations($ax.GetParentIdFromLink(linkId)); - return bubble; - }).bind($ax.features.eventNames.mouseDownName, function() { - var linkId = this.id; - var mouseOverObjectId = _event.mouseOverObjectId; - if($ax.style.IsWidgetDisabled(mouseOverObjectId)) return undefined; - - if(mouseOverObjectId) $ax.style.SetWidgetMouseDown(mouseOverObjectId, true); - $ax.style.SetLinkMouseDown(linkId); - - $ax.annotation.updateLinkLocations($ax.GetParentIdFromLink(linkId)); - - return false; - }).bind($ax.features.eventNames.mouseUpName, function() { - var linkId = this.id; - var mouseOverObjectId = _event.mouseOverObjectId; - if(mouseOverObjectId && $ax.style.IsWidgetDisabled(mouseOverObjectId)) return; - - if(mouseOverObjectId) $ax.style.SetWidgetMouseDown(mouseOverObjectId, false); - $ax.style.SetLinkNotMouseDown(linkId); - - $ax.annotation.updateLinkLocations($ax.GetParentIdFromLink(linkId)); - - }).click(function() { - var elementId = this.id; - var mouseOverObjectId = _event.mouseOverObjectId; - if(mouseOverObjectId && $ax.style.IsWidgetDisabled(mouseOverObjectId)) return undefined; - - return _fireObjectEvent(elementId, 'click', arguments); - }); - } - - // Init inline frames - if (dObj.type == 'inlineFrame') { - var target = dObj.target; - var url = ''; - if(target.includeVariables && target.url) { - var origSrc = target.url; - url = origSrc.toLowerCase().indexOf('http://') == -1 ? $ax.globalVariableProvider.getLinkUrl(origSrc) : origSrc; - - } else if(target.urlLiteral) { - url = $ax.expr.evaluateExpr(target.urlLiteral, $ax.getEventInfoFromEvent(undefined, true, elementId), true); - } - if(url) $jobj($ax.INPUT(elementId)).attr('src', url); - }; - }); - } - $ax.initializeObjectEvents = _initializeObjectEvents; - - $axure.initializeObjectEvents = function (query, refreshType, _) { - //_initializeObjectEvents($ax(query), refreshType); - _initializeObjectEvents($ax(query), $ax.repeater.refreshType.persist); - } - - $ax.event.updateIxStyleEvents = function(elementId) { - _dettachIxStyleEvents(elementId); - _attachIxStyleEvents($ax.getObjectFromElementId(elementId), elementId, $jobj(elementId), true); - } - - function clearMouseDownIxStyle(e) { - if(_event.mouseDownObjectId) { - $('#' + _event.mouseDownObjectId).trigger( - { type: "mouseup", - checkMouseOver: e.data && e.data.checkMouseOver - } - ); - } - } - - var _dettachIxStyleEvents = function(elementId) { - var $element = $jobj(elementId); - $element.off('mouseenter.ixStyle') - .off('mouseleave.ixStyle') - .off($ax.features.eventNames.mouseDownName + '.ixStyle') - .off($ax.features.eventNames.mouseUpName + '.ixStyle'); - } - - var _attachIxStyleEvents = function(dObj, elementId, $element, ignoreHasIxStyles) { - //attach button shape alternate styles - var isDynamicPanel = $ax.public.fn.IsDynamicPanel(dObj.type); - var needsMouseFilter = (ignoreHasIxStyles || $ax.event.HasIxStyles(dObj)) - && dObj.type != 'hyperlink' && !$ax.public.fn.IsLayer(dObj.type) && !isDynamicPanel && dObj.type != $ax.constants.TEXT_TYPE && - !$ax.public.fn.IsRepeater(dObj.type) //&& !$ax.public.fn.IsCheckBox(dObj.type) && !$ax.public.fn.IsRadioButton(dObj.type) - && !$ax.public.fn.IsTreeNodeObject(dObj.type); - if(needsMouseFilter) { - //$element.mouseenter(function () { - $element.on('mouseenter.ixStyle', function () { - var elementId = this.id; - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent && parent.direct) return; - if($.inArray(elementId, _event.mouseOverIds) != -1) return; - _event.mouseOverIds[_event.mouseOverIds.length] = elementId; - - if(elementId == _event.mouseOverObjectId) return; - _event.mouseOverObjectId = elementId; - $ax.style.SetWidgetHover(elementId, true); - $ax.annotation.updateLinkLocations(elementId); - //}).mouseleave(function () { - }).on('mouseleave.ixStyle', function () { - var elementId = this.id; - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent && parent.direct) return; - $ax.splice(_event.mouseOverIds, $.inArray(elementId, _event.mouseOverIds), 1); - - if(elementId == _event.mouseOverObjectId) { - _event.mouseOverObjectId = ''; - } - $ax.style.SetWidgetHover(elementId, false); - $ax.annotation.updateLinkLocations(elementId); - }); - - //$element.bind($ax.features.eventNames.mouseDownName, function () { - $element.on($ax.features.eventNames.mouseDownName + '.ixStyle', function () { - var elementId = this.id; - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent) { - dynamicPanelMouseDown(parent.id); - if(parent.direct) return; - } - _event.mouseDownObjectId = elementId; - //since we don't do mouse capture, it's possible that the mouseup not get triggered later - //in that case, detect the mouseup on document and dragend - $(document).one("mouseup", {checkMouseOver: true}, clearMouseDownIxStyle); - $("#" + elementId).one("dragend", clearMouseDownIxStyle); - - $ax.style.SetWidgetMouseDown(this.id, true); - $ax.annotation.updateLinkLocations(elementId); - //}).bind($ax.features.eventNames.mouseUpName, function () { - }).on($ax.features.eventNames.mouseUpName + '.ixStyle', function (e) { - var elementId = this.id; - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent) { - dynamicPanelMouseUp(parent.id); - if(parent.direct) return; - } - - $(document).off("mouseup", clearMouseDownIxStyle); - - if(_event.mouseDownObjectId) { - $("#" + _event.mouseDownObjectId).off("dragend", clearMouseDownIxStyle); - _event.mouseDownObjectId = ''; - } - if(!$ax.style.ObjHasMouseDown(elementId)) return; - - $ax.style.SetWidgetMouseDown(elementId, false, e.checkMouseOver); - $ax.annotation.updateLinkLocations(elementId); - - //there used to be something we needed to make images click, because swapping out the images prevents the click - // this is a note that we can eventually delete. - }); - - } - }; - - var dynamicPanelMouseDown = function (elementId) { - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent) { - dynamicPanelMouseDown(parent.id); - if(parent.direct) return; - } - _event.mouseDownObjectId = elementId; - $ax.dynamicPanelManager.propagateMouseDown(elementId, true); - }; - - var dynamicPanelMouseUp = function (elementId) { - var parent = $ax.dynamicPanelManager.parentHandlesStyles(elementId); - if(parent) { - dynamicPanelMouseUp(parent.id); - if(parent.direct) return; - } - _event.mouseDownObjectId = ''; - $ax.dynamicPanelManager.propagateMouseDown(elementId, false); - }; - - // Handle key up and key down events - (function() { - var _keyState = {}; - _keyState.ctrl = false; - _keyState.alt = false; - _keyState.shift = false; - _keyState.keyCode = 0; - $ax.event.keyState = function() { - return $ax.deepCopy(_keyState); - }; - - var modifierCodes = [16, 17, 18]; - var clearKeyCode = false; - $ax.event.initKeyEvents = function($query) { - $query.keydown(function (e) { - if(clearKeyCode) { - clearKeyCode = false; - _keyState.keyCode = 0; - } - var elementId = this.id; - - _keyState.ctrl = e.ctrlKey; - - _keyState.alt = e.altKey; - - _keyState.shift = e.shiftKey; - - // If a modifier was pressed, then don't set the keyCode; - if(modifierCodes.indexOf(e.keyCode) == -1) _keyState.keyCode = e.keyCode; - - $ax.setjBrowserEvent(e); - if (!elementId) fireEventThroughContainers('onKeyDown', undefined, false, [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE, $ax.constants.REPEATER], - [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.LAYER_TYPE]); - else _raiseSyntheticEvent(elementId, 'onKeyDown', false, undefined, true); - }); - $query.keyup(function(e) { - var elementId = this.id; - - if (modifierCodes.indexOf(e.keyCode) == -1) clearKeyCode = true; - else if (clearKeyCode) { - clearKeyCode = false; - _keyState.keyCode = 0; - } - - $ax.setjBrowserEvent(e); - // Fire event before updating modifiers. - if (!elementId) fireEventThroughContainers('onKeyUp', undefined, false, [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE, $ax.constants.REPEATER], - [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.LAYER_TYPE]); - else _raiseSyntheticEvent(elementId, 'onKeyUp', false, undefined, true); - - //check if the key is handled before triggering player shortcuts - if(!e.isDefaultPrevented() && !elementId) { - switch(e.which) { - case 188: - $ax.messageCenter.postMessage('previousPage'); - break; - case 190: - $ax.messageCenter.postMessage('nextPage'); - break; - default: - return; // exit this handler for other keys - } - } - - }); - }; - })(); - - // Handle adding mobile events - (function() { - // NOTE: Multi touch is NOT handled currently. - var CLICK_THRESHOLD_PX = 25; - var CLICK_THRESHOLD_PX_SQ = CLICK_THRESHOLD_PX * CLICK_THRESHOLD_PX; - var DBLCLICK_THRESHOLD_MS = 500; - - // Location in page coordinates - var tapDownLoc; - var lastClickEventTime; - - _event.initMobileEvents = function($tapQuery, $moveQuery, elementId) { - if(!$ax.features.supports.mobile) return; - - // Handle touch start - $tapQuery.bind('touchstart', function(e) { - // We do NOT support multiple touches. This isn't necessarily the touch we want. - var touch = e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]; - if(!touch) return; - - tapDownLoc = [touch.pageX, touch.pageY]; - - var time = (new Date()).getTime(); - if(time - lastClickEventTime < DBLCLICK_THRESHOLD_MS) { - var dObj = elementId === '' ? $ax.pageData.page : $ax.getObjectFromElementId(elementId); - var axEventObject = dObj && dObj.interactionMap && dObj.interactionMap['onDoubleClick']; - if(axEventObject) e.preventDefault(); //for Chrome on Android - } - }).bind('touchend', function(e) { - var touch = e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]; - if(!touch || !tapDownLoc || $ax.style.IsWidgetDisabled(elementId)) return; - - var tapUpLoc = [touch.pageX, touch.pageY]; - var xDiff = tapUpLoc[0] - tapDownLoc[0]; - var yDiff = tapUpLoc[1] - tapDownLoc[1]; - - if((xDiff * xDiff + yDiff * yDiff) < CLICK_THRESHOLD_PX_SQ) { - $ax.setjBrowserEvent(e); - _raiseSyntheticEvent(elementId, 'onClick', false, undefined, true); - - var time = (new Date()).getTime(); - if(time - lastClickEventTime < DBLCLICK_THRESHOLD_MS) { - _raiseSyntheticEvent(elementId, 'onDoubleClick', false, undefined, true); - if(e.originalEvent && e.originalEvent.handled) e.preventDefault(); //for iOS - } - lastClickEventTime = time; - } - }); - - // Handles touch move - $moveQuery.bind('touchmove', function(e) { - $ax.setjBrowserEvent(e); - _raiseSyntheticEvent(elementId, 'onMouseMove', false, undefined, true); - if(e.originalEvent && e.originalEvent.handled) e.preventDefault(); - }); - }; - })(); - - // Handle adding device independent click events to non-widgets - (function() { - var CLICK_THRESHOLD_PX = 25; - var CLICK_THRESHOLD_PX_SQ = CLICK_THRESHOLD_PX * CLICK_THRESHOLD_PX; - - // Location in page cooridinates - var tapDownLoc; - - _event.attachClick = function(query, clickHandler) { - if(!$ax.features.supports.mobile) { - query.click(clickHandler); - return; - } - - $(query).bind('touchstart', function(e) { - // We do NOT support multiple touches. This isn't necessarily the touch we want. - var touch = e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]; - if(!touch) return; - - tapDownLoc = [touch.pageX, touch.pageY]; - }); - - $(query).bind('touchend', function(e) { - var touch = e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]; - if(!touch) return; - - var tapUpLoc = [touch.pageX, touch.pageY]; - var xDiff = tapUpLoc[0] - tapDownLoc[0]; - var yDiff = tapUpLoc[1] - tapDownLoc[1]; - - if((xDiff * xDiff + yDiff * yDiff) < CLICK_THRESHOLD_PX_SQ) { - clickHandler(); - } - }); - }; - })(); - - // Handle firing device independent click events on widgets - (function() { - _event.fireClick = function(elementId) { - if(!$ax.features.supports.mobile) { - $('#' + elementId).click(); - return; - } - _raiseSyntheticEvent(elementId, 'onClick', false, undefined, true); - }; - })(); - - var _mouseLocation = $ax.mouseLocation = { x: 0, y: 0 }; - var _lastmouseLocation = $ax.lastMouseLocation = { x: 0, y: 0 }; - - var _updateMouseLocation = function(e, end) { - if(!e) return; - - if(IE_10_AND_BELOW && typeof (e.type) == 'unknown') return; - if(e.type != 'mousemove' && e.type != 'touchstart' && e.type != 'touchmove' && e.type != 'touchend' - && e.type != 'pointermove' && e.type != 'pointerdown' && e.type != 'pointerup') return; - - var newX; - var newY; - if(IE_10_AND_BELOW) { - newX = e.clientX + $('html').scrollLeft(); - newY = e.clientY + $('html').scrollTop(); - } else { - newX = e.pageX; - newY = e.pageY; - } - //var body = $('body'); - //if(body.css('position') == 'relative') newX = Math.round(newX - Number(body.css('left').replace('px', '')) - Math.max(0, ($(window).width() - body.width()) / 2)); - - if(_mouseLocation.x == newX && _mouseLocation.y == newY) return; - - _lastmouseLocation.x = _mouseLocation.x; - _lastmouseLocation.y = _mouseLocation.y; - _mouseLocation.x = newX; - _mouseLocation.y = newY; - - $ax.geometry.tick(_mouseLocation.x, _mouseLocation.y, end); - }; - _event.updateMouseLocation = _updateMouseLocation; - - var _leavingState = function(stateId) { - var mouseOverIds = _event.mouseOverIds; - if(mouseOverIds.length == 0) return; - - var stateQuery = $jobj(stateId); - for(var i = mouseOverIds.length - 1; i >= 0; i--) { - var id = mouseOverIds[i]; - if(stateQuery.find('#' + id).length) { - $ax.splice(mouseOverIds, $.inArray(id, mouseOverIds), 1); - $ax.style.SetWidgetMouseDown(id, false); - $ax.style.SetWidgetHover(id, false); - } - } - - }; - _event.leavingState = _leavingState; - - var _raiseSelectedEvents = function(elementId, value) { - $ax.event.raiseSyntheticEvent(elementId, 'onSelectedChange'); - if(value) $ax.event.raiseSyntheticEvent(elementId, 'onSelect'); - else $ax.event.raiseSyntheticEvent(elementId, 'onUnselect'); - }; - $ax.event.raiseSelectedEvents = _raiseSelectedEvents; - - var _raiseSyntheticEvent = function (elementId, eventName, skipShowDescription, eventInfo, nonSynthetic) { - if ($ax.style.IsWidgetDisabled(elementId) && _shouldStopOnDisabledWidget(eventName)) return; - // Empty string used when this is an event directly on the page. - var dObj = elementId === '' ? $ax.pageData.page : $ax.getObjectFromElementId(elementId); - var axEventObject = dObj && dObj.interactionMap && dObj.interactionMap[eventName]; - if (!axEventObject) return; - - eventInfo = eventInfo || $ax.getEventInfoFromEvent($ax.getjBrowserEvent(), skipShowDescription, elementId); - // $ax.recording.maybeRecordEvent(elementId, eventInfo, axEventObject, new Date().getTime()); - _handleEvent(elementId, eventInfo, axEventObject, false, !nonSynthetic); - }; - $ax.event.raiseSyntheticEvent = _raiseSyntheticEvent; - - var _shouldStopOnDisabledWidget = function (eventName) { - var blackList = ["onLongClick"]; - return blackList.some(x => x === eventName); - } - - var _hasSyntheticEvent = function(scriptId, eventName) { - var dObj = $ax.getObjectFromScriptId(scriptId); - var axEventObject = dObj && dObj.interactionMap && dObj.interactionMap[eventName]; - return Boolean(axEventObject); - }; - $ax.event.hasSyntheticEvent = _hasSyntheticEvent; - - var _addEvent = function (target, eventType, handler, useCapture) { - //this return value is only for debug purpose - var succeed = undefined; - if(target.attachEvent) { - if($ax.features.supports.windowsMobile) { - succeed = target.attachEvent(eventType, handler); - } else { - succeed = target.attachEvent('on' + eventType, handler); - } - } else if(target.addEventListener) { - target.addEventListener(eventType, handler, useCapture); - succeed = true; - } - - return succeed; - } - $ax.event.addEvent = _addEvent; - - var _removeEvent = function(target, eventType, handler, useCapture, skipCheckingWindowsMobile) { - //this return value is only for debug purpose - var succeed = undefined; - - if(target.detachEvent) { - if(!skipCheckingWindowsMobile && $ax.features.supports.windowsMobile) { - succeed = target.detachEvent(eventType, handler); - } else { - succeed = target.detachEvent('on' + eventType, handler); - } - } else if(target.removeEventListener) { - target.removeEventListener(eventType, handler, useCapture); - succeed = true; - } - - return succeed; - } - $ax.event.removeEvent = _removeEvent; - - var _initialize = function() { - $ax.repeater.loadRepeaters(); - - // Make sure key events for page are initialized first. That way they will update the value of key pressed before any other events occur. - _event.initKeyEvents($(window)); - - initSuppressingEvents(); - - // Anything with an item id is in a repeater and should be handled by that repeater. - _initializeObjectEvents($ax(function(obj, elementId) { return !$ax.repeater.getItemIdFromElementId(elementId); })); - - //finally, process the pageload - _pageLoad(); - // _loadDynamicPanelsAndMasters(); - // $ax.repeater.init(); - - // and wipe out the basic links. - $('.basiclink').click(function() { - return false; - }); - }; - _event.initialize = _initialize; - - $ax.event.HasIxStyles = function(diagramObject) { - if(diagramObject.style.stateStyles) return true; - if(diagramObject.adaptiveStyles) { - for(var viewId in diagramObject.adaptiveStyles) { - if(diagramObject.adaptiveStyles[viewId].stateStyles) return true; - } - } - return false; - }; - - $ax.event.HasTextChanged = function(diagramObject) { - if (!$ax.public.fn.IsTextBox(diagramObject.type) && !$ax.public.fn.IsTextArea(diagramObject.type)) return false; - var map = diagramObject.interactionMap; - return map && map.onTextChange; - }; - - $ax.event.TryFireTextChanged = function(elementId) { - var query = $jobj($ax.repeater.applySuffixToElementId(elementId, '_input')); - if(!$ax.hasElementTextChanged(elementId, query.val())) return; - $ax.updateElementText(elementId, query.val()); - - $ax.event.raiseSyntheticEvent(elementId, 'onTextChange'); - }; - - $ax.event.HasSelectionChanged = function(diagramObject) { - if (!$ax.public.fn.IsListBox(diagramObject.type) && !$ax.public.fn.IsComboBox(diagramObject.type)) return false; - var map = diagramObject.interactionMap; - return map && map.onSelectionChange; - }; - - $ax.event.HasKeyUpOrDown = function (diagramObject) { - if($ax.public.fn.IsTextBox(diagramObject.type) || $ax.public.fn.IsTextArea(diagramObject.type)) return true; - var map = diagramObject.interactionMap; - return map && (map.onKeyUp || map.onKeyDown); - }; - - $ax.event.HasCheckedChanged = function(diagramObject) { - if (!$ax.public.fn.IsCheckBox(diagramObject.type) && !$ax.public.fn.IsRadioButton(diagramObject.type)) return false; - var map = diagramObject.interactionMap; - return map && map.onSelectedChange; - }; - - $ax.event.HasClick = function (diagramObject) { - var map = diagramObject.interactionMap; - return map && map.onClick; - }; - - //onload everything now, not only dp and master - var _loadDynamicPanelsAndMasters = function(objects, path, itemId) { - fireEventThroughContainers('onLoad', objects, true, [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE], - [$ax.constants.ALL_TYPE], path, itemId); - }; - $ax.loadDynamicPanelsAndMasters = _loadDynamicPanelsAndMasters; - - var _viewChangePageAndMasters = function(forceSwitchTo) { - fireEventThroughContainers('onAdaptiveViewChange', undefined, true, [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE], - [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE]); - _postAdaptiveViewChanged(forceSwitchTo); - }; - $ax.viewChangePageAndMasters = _viewChangePageAndMasters; - - //if forceSwitchTo is true, we will also update the checkmark in sitemap.js - var _postAdaptiveViewChanged = function(forceSwitchTo) { - //only trigger adaptive view changed if the window is on the mainframe. Also triggered on init, even if default. - try { - if(window.name == 'mainFrame' || - (!CHROME_5_LOCAL && window.parent.$ && window.parent.$('#mainFrame').length > 0)) { - var data = { - viewId: $ax.adaptive.currentViewId, - forceSwitchTo: forceSwitchTo - }; - $axure.messageCenter.postMessage('adaptiveViewChange', data); - } - } catch(e) { } - }; - $ax.postAdaptiveViewChanged = _postAdaptiveViewChanged; - - var _postResize = $ax.postResize = function(e) { - $ax.setjBrowserEvent(e); - return fireEventThroughContainers('onResize', undefined, false, [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE, $ax.constants.REPEATER], - [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE]); - }; - - //fire events for table, menu and tree, including its sub items - var _fireEventsForTableMenuAndTree = function (object, event, skipShowDescription, eventInfo, path, synthetic) { - if (!path) path = []; - var pathCopy = path.slice(); - - pathCopy[path.length] = object.id; - var scriptId = $ax.getScriptIdFromPath(pathCopy); - $ax.event.raiseSyntheticEvent(scriptId, event, skipShowDescription, eventInfo, !synthetic); - - if(object.objects) { - for(var index = 0; index < object.objects.length; index++) { - var subObj = object.objects[index]; - if ($ax.public.fn.IsTableCell(subObj.type)) { - pathCopy[path.length] = subObj.id; - scriptId = $ax.getScriptIdFromPath(pathCopy); - $ax.event.raiseSyntheticEvent(scriptId, event, skipShowDescription, eventInfo, !synthetic); - } else if ($ax.public.fn.IsTable(object.type) || $ax.public.fn.IsMenuObject(object.type) || $ax.public.fn.IsTreeNodeObject(object.type)) { - _fireEventsForTableMenuAndTree(subObj, event, skipShowDescription, eventInfo, path, synthetic); - } - } - } - } - - //remember the scroll bar position, so we can detect scroll up/down - var lastScrollTop; - - var fireEventForPageOrMaster = function (elementId, eventName, interactionMap, isPage, skipShowDescription, synthetic) { - if(!interactionMap) return; - - var axEvent = interactionMap[eventName]; - var scrolling = eventName === "onScroll"; - if (scrolling && !axEvent) axEvent = interactionMap.onScrollUp || interactionMap.onScrollDown; - - if (axEvent) { - var currentEvent = $ax.getjBrowserEvent(); - var eventInfo = $ax.getEventInfoFromEvent(currentEvent, skipShowDescription, elementId); - - if(isPage) { - eventInfo.label = $ax.pageData.page.name; - eventInfo.friendlyType = 'Page'; - } else eventInfo.isMasterEvent = true; - - if(scrolling) _handleScrollEvent(elementId, eventInfo, currentEvent.originalEvent, _event.windowScrollingUp, _event.windowScrollingDown, interactionMap, skipShowDescription, synthetic); - else _handleEvent(elementId, eventInfo, axEvent, skipShowDescription, synthetic); - } - } - // Filters include page, referenceDiagramObject, dynamicPanel, and repeater. - var _callFilterCheck = function(callFilter, type) { - for(var index = 0; index < callFilter.length; index++) { - var currentType = callFilter[index]; - if(currentType === $ax.constants.ALL_TYPE || currentType === type) return true; - } - return false; - }; - - var fireEventThroughContainers = function(eventName, objects, synthetic, searchFilter, callFilter, path, itemId) { - // TODO: may want to pass in this as a parameter. At that point, may want to convert some of them to an option parameter. For now this is the only case - var skipShowDescription = eventName == 'onLoad'; - - // If objects undefined, load page - if(!objects) { - if(_callFilterCheck(callFilter, $ax.constants.PAGE_TYPE)) { - //if scrolling, set direction, later master will know - if(eventName === "onScroll") { - var currentScrollTop = ((SAFARI && IOS) || SHARE_APP) ? $('#ios-safari-html').scrollTop() : $(window).scrollTop(); - _event.windowScrollingUp = currentScrollTop < lastScrollTop; - _event.windowScrollingDown = currentScrollTop > lastScrollTop; - } - - fireEventForPageOrMaster('', eventName, $ax.pageData.page.interactionMap, true, skipShowDescription, synthetic); - } - if(searchFilter.indexOf($ax.constants.PAGE_TYPE) != -1) fireEventThroughContainers(eventName, $ax.pageData.page.diagram.objects, synthetic, searchFilter, callFilter); - //reset and save scrolling info at the end - if(currentScrollTop) { - lastScrollTop = currentScrollTop; - _event.windowScrollingUp = undefined; - _event.windowScrollingDown = undefined; - } - - return; - } - - if(!path) path = []; - - var pathCopy = []; - for(var j = 0; j < path.length; j++) pathCopy[j] = path[j]; - - for(var i = 0; i < objects.length; i++) { - var obj = objects[i]; - pathCopy[path.length] = obj.id; - if (!$ax.public.fn.IsReferenceDiagramObject(obj.type) && !$ax.public.fn.IsDynamicPanel(obj.type) && !$ax.public.fn.IsRepeater(obj.type) && !$ax.public.fn.IsLayer(obj.type)) { - if(_callFilterCheck(callFilter)) { //fire current event for all types - if ($ax.public.fn.IsTable(obj.type) || $ax.public.fn.IsMenuObject(obj.type) || $ax.public.fn.IsTreeNodeObject(obj.type)) { - _fireEventsForTableMenuAndTree(obj, eventName, skipShowDescription, undefined, path, !synthetic); - } else { - var scriptId = $ax.getScriptIdFromPath(pathCopy); - if(scriptId && itemId) scriptId = $ax.repeater.createElementId(scriptId, itemId); - $ax.event.raiseSyntheticEvent(scriptId, eventName, skipShowDescription, undefined, !synthetic); - } - } - continue; - } - - var objId = $ax.getScriptIdFromPath(pathCopy); - // If limboed, move on to next item - if(!objId) continue; - if(itemId) objId = $ax.repeater.createElementId(objId, itemId); - - if($ax.public.fn.IsReferenceDiagramObject(obj.type)) { - if(_callFilterCheck(callFilter, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE)) { - fireEventForPageOrMaster(objId, eventName, $ax.pageData.masters[obj.masterId].interactionMap, false, skipShowDescription, synthetic); - } - if(searchFilter.indexOf($ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE) != -1) fireEventThroughContainers(eventName, $ax.pageData.masters[obj.masterId].diagram.objects, synthetic, searchFilter, callFilter, pathCopy, itemId); - } else if($ax.public.fn.IsDynamicPanel(obj.type)) { - if(_callFilterCheck(callFilter, $ax.constants.DYNAMIC_PANEL_TYPE)) $ax.event.raiseSyntheticEvent(objId, eventName, skipShowDescription, undefined, !synthetic); - - if(searchFilter.indexOf($ax.constants.DYNAMIC_PANEL_TYPE) != -1) { - var diagrams = obj.diagrams; - for(var j = 0; j < diagrams.length; j++) { - fireEventThroughContainers(eventName, diagrams[j].objects, synthetic, searchFilter, callFilter, path, itemId); - } - } - } else if($ax.public.fn.IsRepeater(obj.type)) { - // TODO: possible an option for repeater item? Now fires overall for the repeater - if(_callFilterCheck(callFilter, $ax.constants.REPEATER)) $ax.event.raiseSyntheticEvent(objId, eventName, skipShowDescription, undefined, !synthetic); - if(searchFilter.indexOf($ax.constants.REPEATER) != -1) { - var itemIds = $ax.getItemIdsForRepeater(objId); - for(var j = 0; j < itemIds.length; j++) { - fireEventThroughContainers(eventName, obj.objects, synthetic, searchFilter, callFilter, path, itemIds[j]); - } - } - } else if($ax.public.fn.IsLayer(obj.type)) { - if(_callFilterCheck(callFilter, $ax.constants.LAYER_TYPE)) $ax.event.raiseSyntheticEvent(objId, eventName, skipShowDescription, undefined, !synthetic); - - if(obj.objs && obj.objs.length > 0) { - fireEventThroughContainers(eventName, obj.objs, synthetic, searchFilter, callFilter, path, itemId); - } - } - } - - eventNesting -= 1; - - }; // FOCUS stuff - (function() { - - })(); - - - var _pageLoad = function() { - - // Map of axure event names to pair of what it should attach to, and what the jquery event name is. - var PAGE_AXURE_TO_JQUERY_EVENT_NAMES = { - 'onScroll': [window, 'scroll'], - 'onScrollUp': [window, 'scrollup'], - 'onScrollDown': [window, 'scrolldown'], - //'onResize': [window, 'resize'], - 'onContextMenu': [window, 'contextmenu'] - }; - - var $win = $(window); - if(!$ax.features.supports.mobile) { - PAGE_AXURE_TO_JQUERY_EVENT_NAMES.onClick = ['html', 'click']; - PAGE_AXURE_TO_JQUERY_EVENT_NAMES.onDoubleClick = ['html', 'dblclick']; - PAGE_AXURE_TO_JQUERY_EVENT_NAMES.onMouseMove = ['html', 'mousemove']; - } else { - _event.initMobileEvents($win, $win, ''); - } - - $win.bind($ax.features.eventNames.mouseDownName, _updateMouseLocation); - $win.bind($ax.features.eventNames.mouseUpName, function(e) { _updateMouseLocation(e, true); }); - - $win.scroll(function () { _setCanClick(false); }); - $win.bind($ax.features.eventNames.mouseDownName, function () { _setCanClick(true); }); - - $win.bind($ax.features.eventNames.mouseMoveName, _updateMouseLocation); - $win.scroll($ax.flyoutManager.reregisterAllFlyouts); - - for(key in PAGE_AXURE_TO_JQUERY_EVENT_NAMES) { - if(!PAGE_AXURE_TO_JQUERY_EVENT_NAMES.hasOwnProperty(key)) continue; - (function(axureName) { - var jqueryEventNamePair = PAGE_AXURE_TO_JQUERY_EVENT_NAMES[axureName]; - var actionName = jqueryEventNamePair[1]; - - if(actionName == "scrollup" || actionName == "scrolldown") return; - - var jObj = jqueryEventNamePair[0]; - if ((SAFARI && IOS) || SHARE_APP) jObj = '#ios-safari-html'; - - $(jObj)[actionName](function (e) { - $ax.setjBrowserEvent(e); - if(_shouldIgnoreLabelClickFromCheckboxOrRadioButton(e)) return; - return fireEventThroughContainers(axureName, undefined, false, [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE, $ax.constants.DYNAMIC_PANEL_TYPE, $ax.constants.REPEATER], - [$ax.constants.PAGE_TYPE, $ax.constants.REFERENCE_DIAGRAM_OBJECT_TYPE]); - }); - })(key); - } - - eventNesting -= 1; - lastScrollTop = 0; - }; - _event.pageLoad = _pageLoad; - - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/expr.js b/web/main/static/resources/scripts/axure/expr.js deleted file mode 100644 index 9e9c245..0000000 --- a/web/main/static/resources/scripts/axure/expr.js +++ /dev/null @@ -1,579 +0,0 @@ -// ******* Expr MANAGER ******** // -$axure.internal(function($ax) { - var _expr = $ax.expr = {}; - var _binOpHandlers = { - '&&': function(left, right) { return _binOpOverride(left, right, function(left) { return $ax.getBool(left) && $ax.getBool(right()); }); }, - '||': function(left, right) { return _binOpOverride(left, right, function(left) { return $ax.getBool(left) || $ax.getBool(right()); }); }, - '==': function(left, right) { return isEqual(left, right, true); }, - '!=': function(left, right) { return !isEqual(left, right, true); }, - '>': function(left, right) { return _binOpNum(left, right, function(left, right) { return left > right; }); }, - '<': function(left, right) { return _binOpNum(left, right, function(left, right) { return left < right; }); }, - '>=': function(left, right) { return _binOpNum(left, right, function(left, right) { return left >= right; }); }, - '<=': function(left, right) { return _binOpNum(left, right, function(left, right) { return left <= right; }); } - }; - - var checkOps = function(left, right) { - return left == undefined || right == undefined; - }; - - var isEqual = function (left, right, isFunction) { - if (isFunction) { - //if left and right is function, then get the value - //otherwise left and right should be already the value we want - left = left(); - right = right(); - } - - if(checkOps(left, right)) return false; - - if(left instanceof Date && right instanceof Date) { - if(left.getMilliseconds() != right.getMilliseconds()) return false; - if(left.getSeconds() != right.getSeconds()) return false; - if(left.getMinutes() != right.getMinutes()) return false; - if(left.getHours() != right.getHours()) return false; - if(left.getDate() != right.getDate()) return false; - if(left.getMonth() != right.getMonth()) return false; - if(left.getYear() != right.getYear()) return false; - return true; - } - - if(left instanceof Object && right instanceof Object) { - var prop; - // Go through all of lefts properties and compare them to rights. - for(prop in left) { - if(!left.hasOwnProperty(prop)) continue; - // If left has a property that the right doesn't they are not equal. - if(!right.hasOwnProperty(prop)) return false; - // If any of their properties are not equal, they are not equal. - if(!isEqual(left[prop], right[prop], false)) return false; - } - - for(prop in right) { - // final check to make sure right doesn't have some extra properties that make them not equal. - if(left.hasOwnProperty(prop) != right.hasOwnProperty(prop)) return false; - } - - return true; - } - return $ax.getBool(left) == $ax.getBool(right); - }; - - var _binOpOverride = function(left, right, func) { - left = left(); - if(left == undefined) return false; - var res = func(left, right); - return res == undefined ? false : res; - }; - - var _binOpNum = function(left, right, func) { - var left = left(); - var right = right(); - if(checkOps(left, right)) return false; - - return func(left, Number(right)); - }; - - var _exprHandlers = {}; - _exprHandlers.array = function(expr, eventInfo) { - var returnVal = []; - for(var i = 0; i < expr.items.length; i++) { - returnVal[returnVal.length] = _evaluateExpr(expr.items[i], eventInfo); - } - return returnVal; - }; - - _exprHandlers.binaryOp = function(expr, eventInfo) { - var left = function() { return expr.leftExpr && _evaluateExpr(expr.leftExpr, eventInfo); }; - var right = function() { return expr.rightExpr && _evaluateExpr(expr.rightExpr, eventInfo); }; - - if(left == undefined || right == undefined) return false; - return _binOpHandlers[expr.op](left, right); - }; - - _exprHandlers.block = function(expr, eventInfo) { - var subExprs = expr.subExprs; - for(var i = 0; i < subExprs.length; i++) { - _evaluateExpr(subExprs[i], eventInfo); //ignore the result - } - }; - - _exprHandlers.booleanLiteral = function(expr) { - return expr.value; - }; - - _exprHandlers.nullLiteral = function() { return null; }; - - _exprHandlers.pathLiteral = function(expr, eventInfo) { - if(expr.isThis) return [eventInfo.srcElement]; - if(expr.isFocused && window.lastFocusedControl) { - $ax('#' + window.lastFocusedControl).focus(); - return [window.lastFocusedControl]; - } - if(expr.isTarget) return [eventInfo.targetElement]; - - return $ax.getElementIdsFromPath(expr.value, eventInfo); - }; - - _exprHandlers.panelDiagramLiteral = function(expr, eventInfo) { - var elementIds = $ax.getElementIdsFromPath(expr.panelPath, eventInfo); - var elementIdsWithSuffix = []; - var suffix = '_state' + expr.panelIndex; - for(var i = 0; i < elementIds.length; i++) { - elementIdsWithSuffix[i] = $ax.repeater.applySuffixToElementId(elementIds[i], suffix); - } - return String($jobj(elementIdsWithSuffix).data('label')); - }; - - _exprHandlers.fcall = function(expr, eventInfo) { - var oldTarget = eventInfo.targetElement; - var targets = []; - var fcallArgs = []; - var exprArgs = expr.arguments; - for(var i = 0; i < expr.arguments.length; i++) { - var exprArg = exprArgs[i]; - var fcallArg = ''; - if(targets.length) { - for(var j = 0; j < targets.length; j++) { - if(exprArg == null) { - fcallArgs[j][i] = null; - continue; - } - eventInfo.targetElement = targets[j]; - fcallArg = _evaluateExpr(exprArg, eventInfo); - if(typeof (fcallArg) == 'undefined') return ''; - fcallArgs[j][i] = fcallArg; - } - } else { - if(exprArg == null) { - fcallArgs[i] = null; - continue; - } - fcallArg = _evaluateExpr(exprArg, eventInfo); - if(typeof (fcallArg) == 'undefined') return ''; - fcallArgs[i] = fcallArg; - } - - // We do support null exprArgs... - // TODO: This makes 2 assumptions that may change in the future. 1. The pathLiteral is the always the first arg. 2. there is always only 1 pathLiteral - if(exprArg && exprArg.exprType == 'pathLiteral') { - targets = fcallArg; - - // fcallArgs is now an array of an array of args - for(j = 0; j < targets.length; j++) fcallArgs[j] = [[fcallArg[j]]]; - } - } - - // we want to preserve the target element from outside this function. - eventInfo.targetElement = oldTarget; - - var retval = ''; - if(targets.length) { - // Go backwards so retval is the first item. - for(i = targets.length - 1; i >= 0; i--) { - var args = fcallArgs[i]; - // Add event info to the end - args[args.length] = eventInfo; - retval = _exprFunctions[expr.functionName].apply(this, args); - } - } else fcallArgs[fcallArgs.length] = eventInfo; - return targets.length ? retval : _exprFunctions[expr.functionName].apply(this, fcallArgs); - }; - - _exprHandlers.globalVariableLiteral = function(expr) { - return expr.variableName; - }; - - _exprHandlers.keyPressLiteral = function(expr) { - var keyInfo = {}; - keyInfo.keyCode = expr.keyCode; - keyInfo.ctrl = expr.ctrl; - keyInfo.alt = expr.alt; - keyInfo.shift = expr.shift; - - return keyInfo; - }; - - _exprHandlers.adaptiveViewLiteral = function(expr) { - return expr.id; - }; - - _exprHandlers.optionLiteral = function(expr) { - return expr.value; - } - - var _substituteSTOs = function(expr, eventInfo) { - //first evaluate the local variables - var scope = {}; - for(var varName in expr.localVariables) { - scope[varName] = $ax.expr.evaluateExpr(expr.localVariables[varName], eventInfo); - } - - // TODO: [ben] Date and data object (obj with info for url or image) both need to return non-strings. - var i = 0; - var retval; - var retvalString = expr.value.replace(/\[\[(?!\[)(.*?)\]\](?=\]*)/g, function(match) { - var sto = expr.stos[i++]; - if(sto.sto == 'error') return match; - try { - var result = $ax.evaluateSTO(sto, scope, eventInfo); - } catch(e) { - return match; - } - - if((result instanceof Object) && i == 1 && expr.value.substring(0, 2) == '[[' && - expr.value.substring(expr.value.length - 2) == ']]') { - // If the result was an object, this was the first result, and the whole thing was this expresion. - retval = result; - } - return ((result instanceof Object) && (result.label || result.text)) || result; - }); - // If more than one group returned, the object is not valid - if(i != 1) retval = false; - return retval || retvalString; - }; - - _exprHandlers.htmlLiteral = function (expr, eventInfo) { - eventInfo.htmlLiteral = true; - var html = _substituteSTOs(expr, eventInfo); - eventInfo.htmlLiteral = false - return html; - }; - - _exprHandlers.stringLiteral = function(expr, eventInfo) { - return _substituteSTOs(expr, eventInfo); - }; - - var _exprFunctions = {}; - - _exprFunctions.SetCheckState = function(elementIds, value) { - var toggle = value == 'toggle'; - var boolValue = Boolean(value) && value != 'false'; - - for(var i = 0; i < elementIds.length; i++) { - var query = $ax('#' + elementIds[i]); - query.selected(toggle ? !query.selected() : boolValue); - } - }; - - _exprFunctions.SetSelectedOption = function(elementIds, value) { - for(var i = 0; i < elementIds.length; i++) { - var elementId = elementIds[i]; - var obj = $jobj($ax.INPUT(elementId)); - - if(obj.val() == value) return; - obj.val(value); - - if($ax.event.HasSelectionChanged($ax.getObjectFromElementId(elementId))) $ax.event.raiseSyntheticEvent(elementId, 'onSelectionChange'); - } - }; - - _exprFunctions.SetGlobalVariableValue = function(varName, value) { - $ax.globalVariableProvider.setVariableValue(varName, value); - }; - - _exprFunctions.SetWidgetFormText = function(elementIds, value) { - for(var i = 0; i < elementIds.length; i++) { - var elementId = elementIds[i]; - var inputId = $ax.repeater.applySuffixToElementId(elementId, '_input'); - - var obj = $jobj(inputId); - if(obj.val() == value || (value == '' && $ax.placeholderManager.isActive(elementId))) return; - obj.val(value); - $ax.placeholderManager.updatePlaceholder(elementId, !value); - if($ax.event.HasTextChanged($ax.getObjectFromElementId(elementId))) $ax.event.TryFireTextChanged(elementId); - } - }; - - _exprFunctions.SetFocusedWidgetText = function(elementId, value) { - if(window.lastFocusedControl) { - var elementId = window.lastFocusedControl; - var type = $obj(elementId).type; - if ($ax.public.fn.IsTextBox(type) || $ax.public.fn.IsTextArea(type)) _exprFunctions.SetWidgetFormText([elementId], value); - else _exprFunctions.SetWidgetRichText([elementId], value, true); - } - }; - - _exprFunctions.GetRtfElementHeight = function(rtfElement) { - if(rtfElement.innerHTML == '') rtfElement.innerHTML = ' '; - return rtfElement.offsetHeight; - }; - - _exprFunctions.SetWidgetRichText = function(ids, value, plain) { - // Converts dates, widgetinfo, and the like to strings. - value = _exprFunctions.ToString(value); - - //Replace any newlines with line breaks - var finalValue = value.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>'); - - for(var i = 0; i < ids.length; i++) { - var id = ids[i]; - - // If calling this on button shape, get the id of the rich text panel inside instead - if($obj(id).type !== $ax.constants.LINK_TYPE) id = $ax.GetTextPanelId(id, true); - - var element = window.document.getElementById(id); - $ax.visibility.SetVisible(element, value != ''); - - $ax.style.transformTextWithVerticalAlignment(id, function() { - var spans = $jobj(id).find('span'); - if(plain) { - // Can't set value as text because '<br/>' doesn't actually do a line break - // Can't set vaule as html because it doesn't like '<' and ignores all after it - // Create tags yourself - var lines = value.split(/\r\n|\n/); - //if we are dealing with only one line, just reuse the old one - if(spans.length === 1 && lines.length === 1) { - $(spans[0]).text(value); - return; - } - - // Wrap in span and p, style them accordingly. - var span = $('<span></span>'); - if(spans.length > 0) { - span.attr('style', $(spans[0]).attr('style')); - span.attr('id', $(spans[0]).attr('id')); - } - - if(lines.length == 1) span.text(value); - else { - for(var i = 0; i < lines.length; i++) { - if(i != 0) span.append($('<br />')); - var line = lines[i]; - if(line.length == 0) continue; - - var subSpan = $('<span />'); - subSpan.text(line); - span.append(subSpan); - } - } - - var ps = $jobj(id).find('p'); - if(ps && ps.length) { - ps[0].innerHTML = $('<div></div>').append(span).html();; - if(ps.length > 1) { - for(var i = 1; i < ps.length; i++) { - $(ps[i]).remove(); - } - } - } else { - var p = $('<p></p>'); - p.append(span); - element.innerHTML = $('<div></div>').append(p).html(); - } - } else element.innerHTML = finalValue; - }); - - if(!plain) $ax.style.CacheOriginalText(id, true); - } - }; - - _exprFunctions.GetCheckState = function(ids) { - return $ax('#' + ids[0]).selected(); - }; - - _exprFunctions.GetDisabledState = function (ids) { - return !$ax('#' + ids[0]).enabled(); - }; - - _exprFunctions.GetSelectedOption = function (ids) { - var inputs = $jobj($ax.INPUT(ids[0])); - return inputs.length ? inputs[0].value : ''; - }; - - _exprFunctions.GetNum = function(str) { - //Setting a GlobalVariable to some blank text then setting a widget to the value of that variable would result in 0 not "" - //I have fixed this another way so commenting this should be fine now - //if (!str) return ""; - return isNaN(str) ? str : Number(str); - }; - - _exprFunctions.GetGlobalVariableValue = function(id) { - return $ax.globalVariableProvider.getVariableValue(id); - }; - - _exprFunctions.GetGlobalVariableLength = function(id) { - return _exprFunctions.GetGlobalVariableValue(id).length; - }; - - _exprFunctions.GetWidgetText = function(ids) { - if($ax.placeholderManager.isActive(ids[0])) return ''; - var input = $ax.INPUT(ids[0]); - return $ax('#' + ($jobj(input).length ? input : ids[0])).text(); - }; - - _exprFunctions.GetFocusedWidgetText = function() { - if(window.lastFocusedControl) { - return $ax('#' + window.lastFocusedControl).text(); - } else { - return ""; - } - }; - - _exprFunctions.GetWidgetValueLength = function(ids) { - var id = ids[0]; - if(!id) return undefined; - if($ax.placeholderManager.isActive(id)) return 0; - var obj = $jobj($ax.INPUT(id)); - if(!obj.length) obj = $jobj(id); - var val = obj[0].value || _exprFunctions.GetWidgetText([id]); - return val.length; - }; - - _exprFunctions.GetPanelState = function(ids) { - var id = ids[0]; - if(!id) return undefined; - var stateId = $ax.visibility.GetPanelState(id); - return stateId && String($jobj(stateId).data('label')); - }; - - _exprFunctions.GetWidgetVisibility = function(ids) { - var id = ids[0]; - if(!id) return undefined; - return $ax.visibility.IsIdVisible(id); - }; - - // ***************** Validation Functions ***************** // - - _exprFunctions.IsValueAlpha = function(val) { - var isAlphaRegex = new RegExp("^[a-z\\s]+$", "gi"); - return isAlphaRegex.test(val); - }; - - _exprFunctions.IsValueNumeric = function(val) { - var isNumericRegex = new RegExp("^[0-9,\\.\\s]+$", "gi"); - return isNumericRegex.test(val); - }; - - _exprFunctions.IsValueAlphaNumeric = function(val) { - var isAlphaNumericRegex = new RegExp("^[0-9a-z\\s]+$", "gi"); - return isAlphaNumericRegex.test(val); - }; - - _exprFunctions.IsValueOneOf = function(val, values) { - for(var i = 0; i < values.length; i++) { - var option = values[i]; - if(val == option) return true; - } - //by default, return false - return false; - }; - - _exprFunctions.IsValueNotAlpha = function(val) { - return !_exprFunctions.IsValueAlpha(val); - }; - - _exprFunctions.IsValueNotNumeric = function(val) { - return !_exprFunctions.IsValueNumeric(val); - }; - - _exprFunctions.IsValueNotAlphaNumeric = function(val) { - return !_exprFunctions.IsValueAlphaNumeric(val); - }; - - _exprFunctions.IsValueNotOneOf = function(val, values) { - return !_exprFunctions.IsValueOneOf(val, values); - }; - - _exprFunctions.GetKeyPressed = function(eventInfo) { - return eventInfo.keyInfo; - }; - - _exprFunctions.GetCursorRectangles = function() { - var rects = new Object(); - rects.lastRect = new $ax.drag.Rectangle($ax.lastMouseLocation.x, $ax.lastMouseLocation.y, 1, 1); - rects.currentRect = new $ax.drag.Rectangle($ax.mouseLocation.x, $ax.mouseLocation.y, 1, 1); - return rects; - }; - - _exprFunctions.GetWidgetRectangles = function (elementIds, eventInfo) { - var elementId = elementIds[0]; - var rects = new Object(); - var jObj = $jobj(elementId); - var invalid = jObj.length == 0; - var parent = jObj; - // Or are in valid if no obj can be found, or if it is not visible. - while(parent.length != 0 && !parent.is('body')) { - if(parent.css('display') == 'none') { - invalid = true; - break; - } - parent = parent.parent(); - } - if(invalid) { - rects.lastRect = rects.currentRect = new $ax.drag.Rectangle(-1, -1, -1, -1); - return rects; - } - - var axObj = $ax('#' + elementId); - var boundingRect = axObj.viewportBoundingRect(); - rects.lastRect = new $ax.drag.Rectangle( - boundingRect.left, - boundingRect.top, - boundingRect.width, - boundingRect.height); - //rects.lastRect = new $ax.drag.Rectangle( - // axObj.left(), - // axObj.top(), - // axObj.width(), - // axObj.height()); - - rects.currentRect = rects.lastRect; - return rects; - }; - - _exprFunctions.GetWidget = function(elementId) { - return $ax.getWidgetInfo(elementId[0]); - }; - - _exprFunctions.GetAdaptiveView = function (eventInfo) { - if (eventInfo && eventInfo.srcElement) { - var id = eventInfo.srcElement; - var diagramObject = $ax.getObjectFromElementId(id); - if (diagramObject.owner.type == 'Axure:Master') { - var viewIdChain = $ax.style.getViewIdChain($ax.adaptive.currentViewId || '', id, diagramObject); - if (viewIdChain.length > 0) return viewIdChain[viewIdChain.length - 1]; - else return '19e82109f102476f933582835c373474'; - } - } - return $ax.adaptive.currentViewId || ''; - }; - - _exprFunctions.IsEntering = function(movingRects, targetRects) { - return !movingRects.lastRect.IntersectsWith(targetRects.currentRect) && movingRects.currentRect.IntersectsWith(targetRects.currentRect); - }; - - _exprFunctions.IsLeaving = function(movingRects, targetRects) { - return movingRects.lastRect.IntersectsWith(targetRects.currentRect) && !movingRects.currentRect.IntersectsWith(targetRects.currentRect); - }; - - var _IsOver = _exprFunctions.IsOver = function(movingRects, targetRects) { - return movingRects.currentRect.IntersectsWith(targetRects.currentRect); - }; - - _exprFunctions.IsNotOver = function(movingRects, targetRects) { - return !_IsOver(movingRects, targetRects); - }; - - _exprFunctions.ValueContains = function(inputString, value) { - return inputString.indexOf(value) > -1; - }; - - _exprFunctions.ValueNotContains = function(inputString, value) { - return !_exprFunctions.ValueContains(inputString, value); - }; - - _exprFunctions.ToString = function(value) { - if(value.isWidget) { - return value.text; - } - return String(value); - }; - - var _evaluateExpr = $ax.expr.evaluateExpr = function(expr, eventInfo, toString) { - if(expr === undefined || expr === null) return undefined; - var result = _exprHandlers[expr.exprType](expr, eventInfo); - return toString ? _exprFunctions.ToString(result) : result; - }; - - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/flyout.js b/web/main/static/resources/scripts/axure/flyout.js deleted file mode 100644 index e98303f..0000000 --- a/web/main/static/resources/scripts/axure/flyout.js +++ /dev/null @@ -1,286 +0,0 @@ -// ******* Flyout MANAGER ******** // -$axure.internal(function($ax) { - var _flyoutManager = $ax.flyoutManager = {}; - - var getFlyoutLabel = function(panelId) { - return panelId + '_flyout'; - }; - - var _unregisterPanel = function(panelId, keepShown) { - $ax.geometry.unregister(getFlyoutLabel(panelId)); - if(panelToSrc[panelId]) { - $ax.style.RemoveRolloverOverride(panelToSrc[panelId]); - delete panelToSrc[panelId]; - } - if(!keepShown) { - $ax.action.addAnimation(panelId, $ax.action.queueTypes.fade, function() { - $ax('#' + panelId).hide(); - }); - } - }; - _flyoutManager.unregisterPanel = _unregisterPanel; - - var genPoint = $ax.geometry.genPoint; - - var _updateFlyout = function(panelId) { - var label = getFlyoutLabel(panelId); - if(!$ax.geometry.polygonRegistered(label)) return; - var info = $ax.geometry.getPolygonInfo(label); - var rects = info && info.rects; - - var targetWidget = $ax.getWidgetInfo(panelId); - rects.target = $ax.geometry.genRect(targetWidget); - - // Src will stay the same, just updating - $ax.flyoutManager.registerFlyout(rects, panelId, panelToSrc[panelId]); - - if(!$ax.geometry.checkInsideRegion(label)) _unregisterPanel(panelId); - }; - _flyoutManager.updateFlyout = _updateFlyout; - - var panelToSrc = {}; - var _registerFlyout = function(rects, panelId, srcId) { - var label = _getFlyoutLabel(panelId); - var callback = function(info) { - // If leaving object or already outside it, then unregister, otherwise just return - if(!info.exiting && !info.outside) return; - _unregisterPanel(panelId); - }; - var points = []; - - var lastSrcId = panelToSrc[panelId]; - if(lastSrcId != srcId) { - if(lastSrcId) $ax.style.RemoveRolloverOverride(lastSrcId); - if(srcId) { - $ax.style.AddRolloverOverride(srcId); - panelToSrc[panelId] = srcId; - } else delete panelToSrc[panelId]; - } - - // rects should be one or two rectangles - if(!rects.src) { - var rect = rects.target; - points.push(genPoint(rect.Left(), rect.Top())); - points.push(genPoint(rect.Right(), rect.Top())); - points.push(genPoint(rect.Right(), rect.Bottom())); - points.push(genPoint(rect.Left(), rect.Bottom())); - } else { - var r0 = rects.src; - var r1 = rects.target; - - // Right left of right, left right of left, top below top, bottom above bottom - var rlr = r0.Right() <= r1.Right(); - var lrl = r0.Left() >= r1.Left(); - var tbt = r0.Top() >= r1.Top(); - var bab = r0.Bottom() <= r1.Bottom(); - - var info = { rlr: rlr, lrl: lrl, tbt: tbt, bab: bab }; - - if((rlr && lrl) || (tbt && bab)) { - points = getSmallPolygon(r0, r1, info); - } else { - points = getLargePolygon(r0, r1, info); - } - } - - $ax.geometry.registerPolygon(label, points, callback, { rects: rects }); - }; - _flyoutManager.registerFlyout = _registerFlyout; - - var _getFlyoutLabel = function(panelId) { - return panelId + '_flyout'; - }; - - var _reregisterAllFlyouts = function() { - for(var panelId in panelToSrc) _reregisterFlyout(panelId); - }; - _flyoutManager.reregisterAllFlyouts = _reregisterAllFlyouts; - - var _reregisterFlyout = function(panelId) { - var rects = $ax.geometry.getPolygonInfo(getFlyoutLabel(panelId)).rects; - _registerFlyout(rects, panelId, panelToSrc[panelId]); - }; - - // This is the reduced size polygon connecting r0 to r1 by means of horizontal or vertical lines. - var getSmallPolygon = function(r0, r1, info) { - var points = []; - - // NOTE: currently I make the assumption that if horizontal/vertical connecting lines from the src hit the target - // Meaning if horizontal, rlr and lrl are true, and if vertical, tbt and bab are true. - - var r0Left = r0.Left(); - var r0Right = r0.Right(); - var r0Top = r0.Top(); - var r0Bottom = r0.Bottom(); - var r1Left = r1.Left(); - var r1Right = r1.Right(); - var r1Top = r1.Top(); - var r1Bottom = r1.Bottom(); - - points.push(genPoint(r1Left, r1Top)); - - if(!info.tbt) { - points.push(genPoint(r0Left, r1Top)); - points.push(genPoint(r0Left, r0Top)); - points.push(genPoint(r0Right, r0Top)); - points.push(genPoint(r0Right, r1Top)); - } - - points.push(genPoint(r1Right, r1Top)); - - if(!info.rlr) { - points.push(genPoint(r1Right, r0Top)); - points.push(genPoint(r0Right, r0Top)); - points.push(genPoint(r0Right, r0Bottom)); - points.push(genPoint(r1Right, r0Bottom)); - } - - points.push(genPoint(r1Right, r1Bottom)); - - if(!info.bab) { - points.push(genPoint(r0Right, r1Bottom)); - points.push(genPoint(r0Right, r0Bottom)); - points.push(genPoint(r0Left, r0Bottom)); - points.push(genPoint(r0Left, r1Bottom)); - } - - points.push(genPoint(r1Left, r1Bottom)); - - if(!info.lrl) { - points.push(genPoint(r1Left, r0Bottom)); - points.push(genPoint(r0Left, r0Bottom)); - points.push(genPoint(r0Left, r0Top)); - points.push(genPoint(r1Left, r0Top)); - } - - return points; - }; - - // This is the original algorithm that connects the most extream corners to make polygon - var getLargePolygon = function(r0, r1, info) { - var points = []; - - var r0Left = r0.Left(); - var r0Right = r0.Right(); - var r0Top = r0.Top(); - var r0Bottom = r0.Bottom(); - var r1Left = r1.Left(); - var r1Right = r1.Right(); - var r1Top = r1.Top(); - var r1Bottom = r1.Bottom(); - - // Top lefts - if(info.tbt) { - if(!info.lrl) points.push(genPoint(r0Left, r0Top)); - points.push(genPoint(r1Left, r1Top)); - } else { - if(info.lrl) points.push(genPoint(r1Left, r1Top)); - points.push(genPoint(r0Left, r0Top)); - } - - // Top rights - if(info.tbt) { - points.push(genPoint(r1Right, r1Top)); - if(!info.rlr) points.push(genPoint(r0Right, r0Top)); - } else { - points.push(genPoint(r0Right, r0Top)); - if(info.rlr) points.push(genPoint(r1Right, r1Top)); - } - - // Bottom rights - if(info.bab) { - if(!info.rlr) points.push(genPoint(r0Right, r0Bottom)); - points.push(genPoint(r1Right, r1Bottom)); - } else { - if(info.rlr) points.push(genPoint(r1Right, r1Bottom)); - points.push(genPoint(r0Right, r0Bottom)); - } - - // Bottom Lefts - if(info.bab) { - points.push(genPoint(r1Left, r1Bottom)); - if(!info.lrl) points.push(genPoint(r0Left, r0Bottom)); - } else { - points.push(genPoint(r0Left, r0Bottom)); - if(info.lrl) points.push(genPoint(r1Left, r1Bottom)); - } - return points; - }; -}); - -// ******* Placeholder Manager ********* // - -$axure.internal(function($ax) { - var _placeholderManager = $ax.placeholderManager = {}; - var idToPlaceholderInfo = {}; - - var _registerPlaceholder = function(elementId, text, password) { - idToPlaceholderInfo[elementId] = { text: text, password: password, active: false }; - }; - _placeholderManager.registerPlaceholder = _registerPlaceholder; - - _placeholderManager.refreshPlaceholder = function (elementId) { - var info = idToPlaceholderInfo[elementId]; - if (!info || !info.active) return; - $ax.style.SetWidgetPlaceholder(elementId, true, info.text, info.password); - } - - var _updatePlaceholder = function(elementId, active, clearText) { - var inputId = $ax.repeater.applySuffixToElementId(elementId, '_input'); - - var info = idToPlaceholderInfo[elementId]; - if(!info || info.active == active) return; - info.active = active; - - if(active) var text = info.text; - else if(!ANDROID) text = clearText ? '' : document.getElementById(inputId).value; - else { - var currentText = document.getElementById(inputId).value; - if(!clearText) text = currentText; - else if(currentText == info.text) text = ""; - else { - var lastIndex = currentText.lastIndexOf(info.text); - //here i am assuming the text is always inserted in front - text = currentText.substring(0, lastIndex); - } - } - - $ax.style.SetWidgetPlaceholder(elementId, active, text, info.password); - }; - _placeholderManager.updatePlaceholder = _updatePlaceholder; - - var _isActive = function(elementId) { - var info = idToPlaceholderInfo[elementId]; - return Boolean(info && info.active); - }; - _placeholderManager.isActive = _isActive; - - var _selectRange = function(elementId, start, end) { - $jobj(elementId).each(function() { - if(this.setSelectionRange) { - var validTypes = ["text", "search", "url", "tel", "password"]; - if(this.tagName.toLowerCase() != "input" || validTypes.indexOf(this.type) > -1) { - this.focus(); - this.setSelectionRange(start, end); - } - } else if(this.createTextRange) { - var range = this.createTextRange(); - range.collapse(true); - range.moveEnd('character', end); - range.moveStart('character', start); - range.select(); - } - }); - }; - _placeholderManager.selectRange = _selectRange; - - var _moveCaret = function(id, index) { - var inputIndex = id.indexOf('_input'); - if(inputIndex == -1) return; - var inputId = id.substring(0, inputIndex); - - if(!_isActive(inputId)) return; - _selectRange(id, index, index); - }; - _placeholderManager.moveCaret = _moveCaret; -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/geometry.js b/web/main/static/resources/scripts/axure/geometry.js deleted file mode 100644 index 4bdc0f0..0000000 --- a/web/main/static/resources/scripts/axure/geometry.js +++ /dev/null @@ -1,294 +0,0 @@ -// ******* Region MANAGER ******** // -$axure.internal(function($ax) { - var _geometry = $ax.geometry = {}; - var regionMap = {}; - var regionList = []; - - var _unregister = function(label) { - var regionIndex = regionList.indexOf(label); - if(regionIndex != -1) { - var end = $ax.splice(regionList, regionIndex + 1); - $ax.splice(regionList, regionIndex, regionList.length - regionIndex); - regionList = regionList.concat(end); - } - delete regionMap[label]; - }; - _geometry.unregister = _unregister; - - var clear = function() { - regionMap = {}; - regionList = []; - }; - - var _polygonRegistered = function(label) { - return Boolean(regionMap[label]); - }; - _geometry.polygonRegistered = _polygonRegistered; - - // Must be counterclockwise, or enter/exit will be wrong - var _registerPolygon = function(label, points, callback, info) { - var regionIndex = regionList.indexOf(label); - if(regionIndex == -1) regionList.push(label); - regionMap[label] = { points: points, callback: callback, info: info }; - }; - _geometry.registerPolygon = _registerPolygon; - - var _getPolygonInfo = function(label) { - if(!_polygonRegistered(label)) return undefined; - return regionMap[label].info; - }; - _geometry.getPolygonInfo = _getPolygonInfo; - - - - var _genRect = function(info, roundHalfPixel) { - var x = info.pagex(); - var y = info.pagey(); - var w = info.width(); - var h = info.height(); - - if(roundHalfPixel) { - if(x % 1 != 0) { - x = Math.floor(x); - w++; - } - if(y % 1 != 0) { - y = Math.floor(y); - h++; - } - } - - var r = x + w; - var b = y + h; - - var rect = { - X: function() { return x; }, - Y: function() { return y; }, - Wigth: function() { return w; }, - Height: function() { return h; }, - Left: function() { return x; }, - Right: function() { return r; }, - Top: function() { return y; }, - Bottom: function() { return b; } - }; - return rect; - }; - _geometry.genRect = _genRect; - - var _genPoint = function(x, y) { - return { x: x, y: y }; - }; - _geometry.genPoint = _genPoint; - - var oldPoint = _genPoint(0, 0); - _geometry.tick = function(x, y, end) { - var lastPoint = oldPoint; - var nextPoint = oldPoint = _genPoint(x, y); - var line = { p1: lastPoint, p2: nextPoint }; - if(!regionList.length) return; - - for(var i = 0; i < regionList.length; i++) { - var region = regionMap[regionList[i]]; - var points = region.points; - for(var j = 0; j < points.length; j++) { - var startSegment = points[j]; - var endSegment = points[(j + 1) % points.length]; - var intersectInfo = linesIntersect(line, { p1: startSegment, p2: endSegment }); - if(intersectInfo) { - region.callback(intersectInfo); - break; - } - } - } - - if(end) clear(); - }; - - // Info if the one line touches the other (even barely), false otherwise - // Info includes point, if l1 is entering or exiting l2, and any ties that happened, or parallel info - var linesIntersect = function(l1, l2) { - var retval = {}; - var ties = {}; - - var l1p1 = l1.p1.x < l1.p2.x || (l1.p1.x == l1.p2.x && l1.p1.y < l1.p2.y) ? l1.p1 : l1.p2; - var l1p2 = l1.p1.x < l1.p2.x || (l1.p1.x == l1.p2.x && l1.p1.y < l1.p2.y) ? l1.p2 : l1.p1; - var m1 = (l1p2.y - l1p1.y) / (l1p2.x - l1p1.x); - - var l2p1 = l2.p1.x < l2.p2.x || (l2.p1.x == l2.p2.x && l2.p1.y < l2.p2.y) ? l2.p1 : l2.p2; - var l2p2 = l2.p1.x < l2.p2.x || (l2.p1.x == l2.p2.x && l2.p1.y < l2.p2.y) ? l2.p2 : l2.p1; - var m2 = (l2p2.y - l2p1.y) / (l2p2.x - l2p1.x); - - var l1Vert = l1.p1.x == l1.p2.x; - var l2Vert = l2.p1.x == l2.p2.x; - if(l1Vert || l2Vert) { - if(l1Vert && l2Vert) { - // If the lines don't follow the same path, return - if(l1p1.x != l2p1.x) return false; - // if they never meet, return - if(l1p2.y < l2p1.y || l1p1.y > l2p2.y) return false; - var firstVert = l1p1.y >= l2p1.y ? l1p1 : l2p1; - var secondVert = l1p2.y <= l2p2.y ? l1p2 : l2p2; - // First is from the perspective of l1 - retval.parallel = { - first: l1p1 == l1.p1 ? firstVert : secondVert, - second: l1p2 == l1.p2 ? secondVert : firstVert, - sameDirection: (l1p1 == l1.p1) == (l2p1 == l2.p1) - }; - - return retval; - } - - var x1 = l2Vert ? l1p1.x : l2p1.x; - var x2 = l2Vert ? l1p2.x : l2p2.x; - var xVert = l2Vert ? l2p1.x : l1p1.x; - - var y = l2Vert ? l1p1.y + (xVert - x1) * m1 : l2p1.y + (xVert - x1) * m2; - var y1 = l2Vert ? l2p1.y : l1p1.y; - var y2 = l2Vert ? l2p2.y : l1p2.y; - if(xVert >= x1 && xVert <= x2 && y >= y1 && y <= y2) { - retval.point = { x: xVert, y: y }; - retval.exiting = l2Vert == (y1 == (l2Vert ? l2.p1.y : l1.p1.y)) == (x1 == (l2Vert ? l1.p1.x : l2.p1.x)); - retval.entering = !retval.exiting; - - // Calculate ties - if(x1 == xVert) { - ties[l2Vert ? 'l1' : 'l2'] = (x1 == (l2Vert ? l1.p1.x : l2.p1.x)) ? 'start' : 'end'; - retval.ties = ties; - } else if(x2 == xVert) { - ties[l2Vert ? 'l1' : 'l2'] = (x2 == (l2Vert ? l1.p2.x : l2.p2.x)) ? 'end' : 'start'; - retval.ties = ties; - } - if(y1 == y) { - ties[l2Vert ? 'l2' : 'l1'] = (y1 == (l2Vert ? l2.p1.y : l1.p1.y)) ? 'start' : 'end'; - retval.ties = ties; - } else if(y2 == y) { - ties[l2Vert ? 'l2' : 'l1'] = (y2 == (l2Vert ? l2.p2.y : l1.p2.y)) ? 'end' : 'start'; - retval.ties = ties; - } - - return retval; - } - return false; - } - // If here, no vertical lines - - if(m1 == m2) { - // If the lines don't follow the same path, return - if(l1p1.y != (l2p1.y + (l1p1.x - l2p1.x) * m1)) return false; - // if they never meet, return - if(l1p2.x < l2p1.x || l1p1.x > l2p2.x) return false; - var first = l1p1.x >= l2p1.x ? l1p1 : l2p1; - var second = l1p2.x <= l2p2.x ? l1p2 : l2p2; - // First is from the perspective of l1 - retval.parallel = { - first: l1p1 == l1.p1 ? first : second, - second: l1p2 == l1.p2 ? second : first, - sameDirection: (l1p1 == l1.p1) == (l2p1 == l2.p1) - }; - - return retval; - } - - var x = (l2p1.y - l2p1.x * m2 - l1p1.y + l1p1.x * m1) / (m1 - m2); - - // Check if x is out of bounds - if(x >= l1p1.x && x <= l1p2.x && x >= l2p1.x && x <= l2p2.x) { - var y = l1p1.y + (x - l1p1.x) * m1; - retval.point = { x: x, y: y }; - retval.entering = m1 > m2 == (l1p1 == l1.p1) == (l2p1 == l2.p1); - retval.exiting = !retval.entering; - - // Calculate ties - if(l1.p1.x == x) { - ties.l1 = 'start'; - retval.ties = ties; - } else if(l1.p2.x == x) { - ties.l1 = 'end'; - retval.ties = ties; - } - if(l2.p1.x == x) { - ties.l2 = 'start'; - retval.ties = ties; - } else if(l2.p2.x == x) { - ties.l2 = 'end'; - retval.ties = ties; - } - - return retval; - } - return false; - }; - - var _checkInsideRegion = function(label, point) { - if(!_polygonRegistered(label)) return false; - - return _checkInside(regionMap[label].points, point || $ax.mouseLocation); - }; - _geometry.checkInsideRegion = _checkInsideRegion; - - // Returns true if point is inside the polygon, including ties - var _checkInside = function(polygon, point) { - // Make horizontal line wider than the polygon, with the y of point to test location - var firstX = polygon[0].x; - var secondX = firstX; - var i; - for(i = 1; i < polygon.length; i++) { - var polyX = polygon[i].x; - firstX = Math.min(firstX, polyX); - secondX = Math.max(secondX, polyX); - } - var line = { - p1: _genPoint(--firstX, point.y), - p2: _genPoint(++secondX, point.y) - }; - - // If entered true, with closest intersection says you are inside the polygon. - var entered = false; - // Closest is the closest intersection to the left of the point - var closest = line.p1.x; - // This is for if intersections hit the same point, to find out which is correct - var cos = -2; - - var getCos = function(line) { - var x = line.p2.x - line.p1.x; - var y = line.p2.y - line.p1.y; - return x / Math.sqrt(x * x + y * y); - }; - - for(i = 0; i < polygon.length; i++) { - var polyLine = { p1: polygon[i], p2: polygon[(i + 1) % polygon.length] }; - var intersectInfo = linesIntersect(line, polyLine); - if(!intersectInfo) continue; - - if(intersectInfo.parallel) { - // Only really care about this if it actually touches the point - if(intersectInfo.parallel.first.x <= point.x && intersectInfo.parallel.second.x >= point.x) return true; - continue; - } - - var intersectionX = intersectInfo.point.x; - if(intersectionX > point.x || intersectionX < closest) continue; - if(intersectionX == point.x) return true; - - // If closer than last time, reset cosine. - if(intersectionX != closest) cos = -2; - - // For getting cosine, need to possibly reverse the direction of polyLine. - if(intersectInfo.ties) { - // Tie must be on l2, if the ties is end, reverse so cosine indicates how close the angle is to that of 'point' from here. - if(intersectInfo.ties.l2 == 'end') polyLine = { p1: polyLine.p2, p2: polyLine.p1 }; - } else { - // It is on both side, so you can take the larger one - if(polyLine.p1.x > polyLine.p2.x) polyLine = { p1: polyLine.p2, p2: polyLine.p1 }; - } - var currCos = getCos(polyLine); - if(currCos > cos) { - cos = currCos; - closest = intersectionX; - entered = intersectInfo.entering; - } - } - return entered; - }; - _geometry.checkInside = _checkInside; -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/globals.js b/web/main/static/resources/scripts/axure/globals.js deleted file mode 100644 index 0c5c4e8..0000000 --- a/web/main/static/resources/scripts/axure/globals.js +++ /dev/null @@ -1,7 +0,0 @@ -$axure.internal(function($ax) { - var _globals = $ax.globals = {}; - - $ax.globals.MaxZIndex = 1000; - $ax.globals.MinZIndex = -1000; - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/ie.js b/web/main/static/resources/scripts/axure/ie.js deleted file mode 100644 index cd99447..0000000 --- a/web/main/static/resources/scripts/axure/ie.js +++ /dev/null @@ -1,344 +0,0 @@ - -//// ******* Internet Explorer MANAGER ******** // -////this is to handle all the stupid IE Stuff -//$axure.internal(function($ax) { -// if(!IE_10_AND_BELOW) return; - -// var _ieColorManager = {}; -// if(Number(BROWSER_VERSION) < 9) $ax.ieColorManager = _ieColorManager; - -// var _applyIEFixedPosition = function() { -// if(Number(BROWSER_VERSION) >= 7) return; - -// $axure(function(diagramObject) { return diagramObject.fixedVertical; }).$() -// .appendTo($('body')) -// .css('position', 'absolute').css('margin-left', 0 + 'px').css('margin-top', 0 + 'px'); - -// var handleScroll = function() { -// $axure(function(diagramObject) { return diagramObject.fixedVertical; }) -// .each(function(diagramObject, elementId) { -// var win = $(window); -// var windowWidth = win.width(); -// var windowHeight = win.height(); -// var windowScrollLeft = win.scrollLeft(); -// var windowScrollTop = win.scrollTop(); - -// var newLeft = 0; -// var newTop = 0; -// var elementQuery = $('#' + elementId); -// var elementAxQuery = $ax('#' + elementId); -// var width = elementAxQuery.width(); -// var height = elementAxQuery.height(); - -// var horz = diagramObject.fixedHorizontal; -// if(horz == 'left') { -// newLeft = windowScrollLeft + diagramObject.fixedMarginHorizontal; -// } else if(horz == 'center') { -// newLeft = windowScrollLeft + ((windowWidth - width) / 2) + diagramObject.fixedMarginHorizontal; -// } else if(horz == 'right') { -// newLeft = windowScrollLeft + windowWidth - width - diagramObject.fixedMarginHorizontal; -// } - -// var vert = diagramObject.fixedVertical; -// if(vert == 'top') { -// newTop = windowScrollTop + diagramObject.fixedMarginVertical; -// } else if(vert == 'middle') { -// newTop = windowScrollTop + ((windowHeight - height) / 2) + diagramObject.fixedMarginVertical; -// } else if(vert == 'bottom') { -// newTop = windowScrollTop + windowHeight - height - diagramObject.fixedMarginVertical; -// } -// elementQuery.css('top', newTop + 'px').css('left', newLeft + 'px'); -// }); -// }; - -// $(window).scroll(handleScroll); -// $axure.resize(handleScroll); -// handleScroll(); -// }; - -// var _applyBackground = function() { -// if(Number(BROWSER_VERSION) >= 9) return; - -// var styleChain = $ax.adaptive.getAdaptiveIdChain($ax.adaptive.currentViewId); -// var argb = _getArgb($ax.pageData.page, styleChain); -// var hexColor = _getHexColor(argb, false); -// if(hexColor) $('body').css('background-color', hexColor); - -// _applyBackgroundToQuery($ax('*')); -// }; - -// var _applyBackgroundToQuery = function(query) { -// if(Number(BROWSER_VERSION) >= 9) return; - -// var styleChain = $ax.adaptive.getAdaptiveIdChain($ax.adaptive.currentViewId); -// query.each(function(obj, elementId) { -// if ($ax.public.fn.IsDynamicPanel(obj.type)) { -// var stateCount = obj.diagrams.length; -// for(var j = 0; j < stateCount; j++) { -// var stateId = $ax.repeater.applySuffixToElementId(elementId, '_state' + j); -// var argb = _getArgb(obj.diagrams[j], styleChain); -// var hexColor = _getHexColor(argb, true); -// if(hexColor) $jobj(stateId).css('background-color', hexColor); -// } -// } else if ($ax.public.fn.IsRepeater(obj.type)) { - -// } -// }); -// }; -// _ieColorManager.applyBackground = _applyBackgroundToQuery; - -// var _getArgb = function(diagram, styleChain) { -// var argb = undefined; -// for(var i = 0; i < styleChain.length && !argb; i++) { -// var style = diagram.adaptiveStyles[styleChain[i]]; -// argb = style.fill && style.fill.color; -// } -// if(!argb) argb = diagram.style.fill.color; -// return argb; -// }; - -// var gMult = 256; -// var rMult = gMult * 256; -// var aMult = rMult * 256; - -// var _getHexColor = function(argb, allowWhite) { -// var a = Math.floor(argb / aMult); -// argb -= a * aMult; - -// var r = Math.floor(argb / rMult); -// argb -= r * rMult; - -// var g = Math.floor(argb / gMult); -// var b = argb - g * gMult; - -// return _getColorFromArgb(a, r, g, b, allowWhite); -// }; - -// var _getColorFromArgb = function(a, r, g, b, allowWhite) { -// if(Number(BROWSER_VERSION) >= 9) return undefined; - -// //convert the color with alpha to a color with no alpha (assuming white background) -// r = Math.min((r * a) / 255 + 255 - a, 255); -// g = Math.min((g * a) / 255 + 255 - a, 255); -// b = Math.min((b * a) / 255 + 255 - a, 255); - -// if(a == 0) return undefined; -// if(!allowWhite && (r == 255 && g == 255 && b == 255)) return undefined; - -// var color = '#'; -// color += Math.floor(r / 16).toString(16); -// color += Math.floor(r % 16).toString(16); -// color += Math.floor(g / 16).toString(16); -// color += Math.floor(g % 16).toString(16); -// color += Math.floor(b / 16).toString(16); -// color += Math.floor(b % 16).toString(16); -// return color; -// }; -// _ieColorManager.getColorFromArgb = _getColorFromArgb; - -// var getIEOffset = function(transform, rect) { -// var translatedVertexes = [ -// $axure.utils.Vector2D(0, 0), //we dont translate, so the orgin is fixed -// transform.mul($axure.utils.Vector2D(0, rect.height)), -// transform.mul($axure.utils.Vector2D(rect.width, 0)), -// transform.mul($axure.utils.Vector2D(rect.width, rect.height))]; - -// var minX = 0, minY = 0, maxX = 0, maxY = 0; -// $.each(translatedVertexes, function(index, p) { -// minX = Math.min(minX, p.x); -// minY = Math.min(minY, p.y); -// maxX = Math.max(maxX, p.x); -// maxY = Math.max(maxY, p.y); -// }); - -// return $axure.utils.Vector2D( -// (maxX - minX - rect.width) / 2, -// (maxY - minY - rect.height) / 2); -// }; - -// var _filterFromTransform = function(transform) { -// return "progid:DXImageTransform.Microsoft.Matrix(M11=" + transform.m11 + -// ", M12=" + transform.m12 + ", M21=" + transform.m21 + -// ", M22=" + transform.m22 + ", SizingMethod='auto expand')"; -// }; - -// var _applyIERotation = function() { -// if(Number(BROWSER_VERSION) >= 9) return; - -// $axure(function(diagramObject) { -// return ((diagramObject.style.rotation && Math.abs(diagramObject.style.rotation) > 0.1) -// || (diagramObject.style.textRotation && Math.abs(diagramObject.style.textRotation) > 0.1)) -// && !diagramObject.isContained; -// }).each(function(diagramObject, elementId) { -// var rotation = diagramObject.style.rotation || 0; -// var $element = $('#' + elementId); -// var axElement = $ax('#' + elementId); -// var width = axElement.width(); -// var height = axElement.height(); -// var originX = width / 2; -// var originY = height / 2; - -// var shapeIeOffset; -// $element.children().each(function() { -// var $child = $(this); -// var axChild = $ax('#' + $child.attr('id')); -// var childWidth = axChild.width(); -// var childHeight = axChild.height() + $child.position().top; -// var centerX = $child.position().left + (childWidth / 2); -// var centerY = $child.position().top + (childHeight / 2); -// var deltaX = centerX - originX; -// var deltaY = centerY - originY; - -// var effectiveRotation = rotation; -// var textObject = $ax.getObjectFromElementId($child.attr('id')); -// if(textObject) { -// if(textObject.style.textRotation) effectiveRotation = textObject.style.textRotation; -// else return; -// } - -// var transform = $ax.utils.Matrix2D.identity().rotate(effectiveRotation); -// var filter = _filterFromTransform(transform); - -// $child.css('filter', filter) -// .width(childWidth + 1) -// .height(childHeight + 1); - -// var p = transform.mul($ax.utils.Vector2D(deltaX, deltaY)); -// var ieOffset = getIEOffset(transform, { width: childWidth, height: childHeight }); -// if(!textObject) { -// shapeIeOffset = ieOffset; -// } else { -// // This is a close approximation, but not exact -// if(diagramObject.style.verticalAlignment != 'top') ieOffset.y -= shapeIeOffset.y + Math.abs(shapeIeOffset.x); -// } - -// $child.css("margin-left", -ieOffset.x - deltaX + p.x).css("margin-top", -ieOffset.y - deltaY + p.y); -// }); -// }); -// }; - -// var _fixIEStretchBackground = function() { -// if(Number(BROWSER_VERSION) >= 9) return; -// var pageStyle = $ax.adaptive.getPageStyle(); -// if(!pageStyle.imageRepeat || pageStyle.imageRepeat == 'auto') return; - -// $('body').css('background-image', 'none'); -// var viewId = $ax.adaptive.currentViewId; -// var imageInfo = viewId ? $ax.pageData.viewIdToBackgroundImageInfo && $ax.pageData.viewIdToBackgroundImageInfo[viewId] : $ax.pageData.defaultBackgroundImageInfo; -// if(imageInfo && imageInfo.path) { -// if($('#bg_img').length == 0) $('body').append('<img id="bg_img"/>'); -// $('#bg_img').attr('src', imageInfo.path).css('position', 'fixed').css('z-index', '-10000'); -// _resizeIEBackground(); -// } else $('#bg_img').remove(); -// }; - -// var _resizeIEBackground = function() { -// if(Number(BROWSER_VERSION) >= 9) return; -// //var page = $ax.pageData.page; -// var viewId = $ax.adaptive.currentViewId; -// var pageStyle = $ax.adaptive.getPageStyle(); -// if(!$ax.pageData.defaultBackgroundImageInfo && !$ax.pageData.viewIdToBackgroundImageInfo) return; -// var imageInfo = viewId ? $ax.pageData.viewIdToBackgroundImageInfo[viewId] : $ax.pageData.defaultBackgroundImageInfo; -// if(!imageInfo) return; -// var imageWidth = imageInfo.width; -// var imageHeight = imageInfo.height; -// var windowWidth = $(window).width(); -// var windowHeight = $(window).height(); -// var isCover = pageStyle.imageRepeat == 'cover'; - -// var wRatio = windowWidth / imageWidth; -// var hRatio = windowHeight / imageHeight; -// var ratio = wRatio; -// if(isCover) { -// if(hRatio > wRatio) ratio = hRatio; -// } else { -// if(hRatio < wRatio) ratio = hRatio; -// } -// var width = imageWidth * ratio; -// var height = imageHeight * ratio; - -// var left = '0px'; -// if((isCover && width > windowWidth) || (!isCover && width < windowWidth)) { -// if(pageStyle.imageHorizontalAlignment == 'center') { -// left = ((windowWidth - width) / 2) + 'px'; -// } else if(pageStyle.imageHorizontalAlignment == 'far') { -// left = (windowWidth - width) + 'px'; -// } -// } - -// var top = '0px'; -// if((isCover && height > windowHeight) || (!isCover && height < windowHeight)) { -// if(pageStyle.imageVerticalAlignment == 'center') { -// top = ((windowHeight - height) / 2) + 'px'; -// } else if(pageStyle.imageVerticalAlignment == 'far') { -// top = (windowHeight - height) + 'px'; -// } -// } - -// $('#bg_img').css('top', top).css('left', left).css('width', width).css('height', height); -// }; - -// var _fixAllPngs = function() { -// if(!(/MSIE ((5\.5)|6)/.test(window.navigator.userAgent) && window.navigator.platform == "Win32")) return; - -// $('img[src$=".png"]').each(function() { -// if(!this.complete) { -// this.onload = function() { $axure.utils.fixPng(this); }; -// } else { -// $axure.utils.fixPng(this); -// } -// }); -// }; - -// var _fixInputSize = function() { -// if(Number(BROWSER_VERSION) >= 8 || window.navigator.userAgent.indexOf("Trident/4.0") > -1) return; -// var inputs = $('input').not(':input[type=button], :input[type=submit], :input[type=radio], :input[type=checkbox]'); -// inputs.each(function() { -// var $input = $(this); -// var axInput = $ax('#' + $input.attr('id')); -// $input.css('height', (axInput.height() - 4 + 'px')).css('width', (axInput.width() - 2 + 'px')); -// }); - -// var textAreas = $($ax.constants.TEXT_AREA_TYPE); -// textAreas.each(function() { -// var $textArea = $(this); -// var axText = $ax('#' + $textArea.attr('id')); -// $textArea.css('height', (axText.height() - 6 + 'px')).css('width', (axText.width() - 6 + 'px')); -// }); -// }; - -// var _fixInputBackground = function() { -// var inputs = $('input').not(':input[type=button], :input[type=submit], :input[type=radio], :input[type=checkbox]'); -// inputs = inputs.add($($ax.constants.TEXT_AREA_TYPE)); -// inputs.each(function() { -// var $input = $(this); -// if($input.css('background-color') == 'transparent') { -// $input.css('background-image', 'url(../../transparent.gif)'); -// } else { -// $input.css('background-image', ''); -// } -// }); -// }; - -// $(document).ready(function() { -// _fixIEStretchBackground(); -// _applyIEFixedPosition(); -// $axure.resize(function() { -// _resizeIEBackground(); -// }); -// $ax.adaptive.bind('viewChanged', function() { -// _fixIEStretchBackground(); -// _applyBackground(); -// _fixInputBackground(); -// }); - - -// _fixAllPngs(); -// _applyIERotation(); -// _applyBackground(); -// _fixInputSize(); -// _fixInputBackground(); -// }); - - -//}); diff --git a/web/main/static/resources/scripts/axure/init.temp.js b/web/main/static/resources/scripts/axure/init.temp.js deleted file mode 100644 index a6869f1..0000000 --- a/web/main/static/resources/scripts/axure/init.temp.js +++ /dev/null @@ -1,326 +0,0 @@ -$axure.internal(function($ax) { - - $(window.document).ready(function () { - - //var readyStart = (new Date()).getTime(); - - //this is because the page id is not formatted as a guid - var pageId = $ax.pageData.page.packageId; - - var pageData = { - id: pageId, - pageName: $ax.pageData.page.name, - location: window.location.toString(), - notes: $ax.pageData.page.notes, - widgetNotes: $ax.pageData.page.annotations, - //clipToView: $ax.pageData.clipToView, - defaultAdaptiveView: $ax.pageData.defaultAdaptiveView, - adaptiveViews: $ax.pageData.adaptiveViews, - masterNotes: [] - }; - - var fnPrefix = ''; - function pushNextPrefix() { - if (fnPrefix.length == 0) fnPrefix = 'A'; - else fnPrefix = fnPrefix[0] == 'Z' ? 'A'.repeat(fnPrefix.length + 1) : String.fromCharCode(fnPrefix.charCodeAt(0) + 1).repeat(fnPrefix.length); - } - - function populateNotes(pageForNotes) { - for (var master in pageForNotes.masters) { - //var master = pageForNotes.masters[i]; - var masterData = pageForNotes.masters[master]; - var hasWidgetNotes = masterData.annotations && masterData.annotations.length > 0; - if ((master.notes && !$.isEmptyObject(masterData.notes)) || hasWidgetNotes) { - if(hasWidgetNotes) pushNextPrefix(); - var m = {}; - m.pageName = masterData.name; - m.notes = masterData.notes; - m.widgetNotes = masterData.annotations; - pageData.masterNotes.push(m); - if(hasWidgetNotes) populateOwnerToFn(m.widgetNotes); - } - populateNotes(master); - } - } - - var ownerToFns = {}; - function populateOwnerToFn(widgetNotes) { - if(typeof widgetNotes == 'undefined') return false; - for (var i = 0; i < widgetNotes.length; i++) { - var widgetNote = widgetNotes[i]; - widgetNote['fn'] = fnPrefix + widgetNote['fn']; - var fn = widgetNote['fn']; - var ownerId = widgetNote['ownerId']; - if (ownerId !== undefined && ownerId.length > 0) { - var ownerLabels = ownerToFns[ownerId]; - if (ownerLabels == undefined) ownerLabels = []; - ownerLabels.push(fn); - ownerToFns[ownerId] = ownerLabels; - } - } - } - - populateOwnerToFn(pageData.widgetNotes); - populateNotes($ax.pageData); - pageData.ownerToFns = ownerToFns; - - $ax.pageData.notesData = pageData; - - //var anns = []; - //$ax('*').each(function (dObj, elementId) { - // pushAnnotation(dObj, elementId); - //}); - - //function pushAnnotation(dObj, elementId) { - // var ann = dObj.annotation; - // if(ann) { - // ann = $ax.deepCopy(ann); - // ann["id"] = elementId; - // ann["label"] = dObj.label + " (" + dObj.friendlyType + ")"; - // anns.push(ann); - // } - - // if(dObj.type === 'repeater' && dObj.objects) { - // //if it's repeater, save the id as repeaterId@scriptId - // for(var i = 0, len = dObj.objects.length; i < len; i++) { - // var child = dObj.objects[i]; - // var scriptId = $ax.getScriptIdFromPath([child.id], elementId); - // pushAnnotation(child, elementId + '@' + scriptId); - // } - // } - //} - - //pageData.widgetNotes = anns; - - //only trigger the page.data setting if the window is on the mainframe - var isMainFrame = false; - try { - if(window.name == 'mainFrame' || - (!CHROME_5_LOCAL && window.parent.$ && window.parent.$('#mainFrame').length > 0)) { - isMainFrame = true; - - $ax.messageCenter.addMessageListener(function(message, data) { - if(message == 'finishInit') { - _processTempInit(); - } - }); - - $axure.messageCenter.setState('page.data', pageData); - window.focus(); - } - } catch(e) { } - - //attach here for chrome local - //$(window).on('load', function() { - // $ax.style.initializeObjectTextAlignment($ax('*')); - //}); - - if(!isMainFrame) _processTempInit(); - }); - - var touchCount = 0; - var lastTouch = Date.now(); - var _registerTouchCount = $ax.registerTouchCount = function (e) { - var now = Date.now(); - if (now - lastTouch < 375) { - if (++touchCount === 3) { - $(':input').blur(); - $ax.messageCenter.postMessage('tripleClick', true); - e.preventDefault(); - }; - } else { - touchCount = 1; - } - lastTouch = now; - }; - - // Block IOS stalling second tap. - // Stop third click from also clicking mobile card - var _clearTouchCount = $ax.clearTouchCount = function (e) { - if (touchCount === 3) { - touchCount = 0; - e.preventDefault(); - } - }; - - var _processTempInit = function() { - //var start = (new Date()).getTime(); - //var end = (new Date()).getTime(); - //window.alert('elapsed ' + (end - start)); - - $('iframe').each(function() { - var origSrc = $(this).attr('basesrc'); - - var $this = $(this); - if(origSrc) { - var newSrcUrl = origSrc.toLowerCase().indexOf('http://') == -1 ? $ax.globalVariableProvider.getLinkUrl(origSrc) : origSrc; - $this.attr('src', newSrcUrl); - } - - if(IOS) { - $this.parent().css('overflow', 'auto').css('-webkit-overflow-scrolling', 'touch').css('-ms-overflow-x', 'hidden').css('overflow-x', 'hidden'); - } - }); - - $axure.messageCenter.addMessageListener(function(message, data) { - if(message == 'setGlobalVar') { - $ax.globalVariableProvider.setVariableValue(data.globalVarName, data.globalVarValue, true); - } - }); - - window.lastFocusedClickable = null; - var _lastFocusedClickableSelector = 'input, a'; - var shouldOutline = true; - - $ax(function (dObj) { return dObj.tabbable; }).each(function (dObj, elementId) { - if ($ax.public.fn.IsLayer(dObj.type)) $ax.event.layerMapFocus(dObj, elementId); - var focusableId = $ax.event.getFocusableWidgetOrChildId(elementId); - var $focusable = $('#' + focusableId); - $focusable.attr("tabIndex", 0); - if($focusable.is('div') || $focusable.is('img')) { - $focusable.bind($ax.features.eventNames.mouseDownName, function() { - shouldOutline = false; - }); - attachFocusAndBlur($focusable); - } - }); - - $(window.document).bind($ax.features.eventNames.mouseUpName, function() { - shouldOutline = true; - }); - - attachFocusAndBlur($(_lastFocusedClickableSelector)); - - function attachFocusAndBlur($query) { - $query.focus(function () { - if(shouldOutline) { - $(this).css('outline', ''); - } else { - $(this).css('outline', 'none'); - } - window.lastFocusedClickable = this; - }).blur(function () { - if(window.lastFocusedClickable == this) window.lastFocusedClickable = null; - }); - } - - $(window.document).bind('keyup', function (e) { - switch(e.which) { - case 13: - case 32: - if(window.lastFocusedClickable) $(window.lastFocusedClickable).click(); - break; - default: return; // exit this handler for other keys - } - }); - - //if($ax.document.configuration.hideAddress) { - // $(window).on('load', function() { - // window.setTimeout(function() { - // window.scrollTo(0, 0.9); - // }, 0); - // }); - //} - - //if($ax.document.configuration.preventScroll) { - // $(window.document).bind('touchmove', function(e) { - // var inScrollable = $ax.legacy.GetScrollable(e.target) != window.document.body; - // if(!inScrollable) { - // e.preventDefault(); - // } - // }); - - // $ax(function(diagramObject) { - // return $ax.public.fn.IsDynamicPanel(diagramObject.type) && diagramObject.scrollbars != 'none'; - // }).$().children().bind('touchstart', function() { - // var target = this; - // var top = target.scrollTop; - // if(top <= 0) target.scrollTop = 1; - // if(top + target.offsetHeight >= target.scrollHeight) target.scrollTop = target.scrollHeight - target.offsetHeight - 1; - // }); - //} - - if(OS_MAC && WEBKIT) { - $ax(function(diagramObject) { - return $ax.public.fn.IsComboBox(diagramObject.type); - }).each(function(obj, id) { - $jobj($ax.INPUT(id)).css('-webkit-appearance', 'menulist-button'); - }); - } - - if($ax.features.supports.mobile) { - $('html').first().on('touchstart', _registerTouchCount); - $('html').first().on('touchend', _clearTouchCount); - - // Stop pinch zoom (stopping all gestures for now) - // Gesturestart is only supported in Safari - if (SAFARI) { - document.addEventListener("gesturestart", function (e) { - e.preventDefault(); - }); - } - } - - $ax.annotation.initialize(); - - $ax.legacy.BringFixedToFront(); - $ax.event.initialize(); - $ax.style.initialize(); - $ax.visibility.initialize(); - $ax.repeater.initialize(); - $ax.dynamicPanelManager.initialize(); //needs to be called after visibility is initialized - $ax.adaptive.initialize(); - $ax.loadDynamicPanelsAndMasters(); - $ax.adaptive.loadFinished(); - var start = (new Date()).getTime(); - $ax.repeater.initRefresh(); - var end = (new Date()).getTime(); - console.log('loadTime: ' + (end - start) / 1000); - $ax.style.prefetch(); - - $(window).resize(); - - //var readyEnd = (new Date()).getTime(); - //window.alert('elapsed ' + (readyEnd - readyStart)); - }; -}); - -/* extend canvas */ -var gv_hasCanvas = false; -(function() { - var _canvas = document.createElement('canvas'), proto, abbrev; - if(gv_hasCanvas = !!(_canvas.getContext && _canvas.getContext('2d')) && typeof (CanvasGradient) !== 'undefined') { - function chain(func) { - return function() { - return func.apply(this, arguments) || this; - }; - } - - with(proto = CanvasRenderingContext2D.prototype) for(var func in abbrev = { - a: arc, - b: beginPath, - n: clearRect, - c: clip, - p: closePath, - g: createLinearGradient, - f: fill, - j: fillRect, - z: function(s) { this.fillStyle = s; }, - l: lineTo, - w: function(w) { this.lineWidth = w; }, - m: moveTo, - q: quadraticCurveTo, - h: rect, - r: restore, - o: rotate, - s: save, - x: scale, - y: function(s) { this.strokeStyle = s; }, - u: setTransform, - k: stroke, - i: strokeRect, - t: translate - }) proto[func] = chain(abbrev[func]); - CanvasGradient.prototype.a = chain(CanvasGradient.prototype.addColorStop); - } -})(); diff --git a/web/main/static/resources/scripts/axure/ios.js b/web/main/static/resources/scripts/axure/ios.js deleted file mode 100644 index 15333b7..0000000 --- a/web/main/static/resources/scripts/axure/ios.js +++ /dev/null @@ -1,91 +0,0 @@ -$axure.internal(function ($ax) { - if ((IOS && SAFARI) || SHARE_APP) { - var outerHtml = document.documentElement; - outerHtml.id = 'ios-safari'; - var html = document.createElement('html'); - html.id = 'ios-safari-html'; - outerHtml.appendChild(html); - var body = document.body; - html.appendChild(body); - Object.defineProperty(document, 'body', { - get: function () { - return body; - } - }); - var fixedBody = document.createElement('body'); - fixedBody.id = 'ios-safari-fixed'; - outerHtml.appendChild(fixedBody); - var fixedBase = document.createElement('div'); - fixedBase.id = 'base-fixed'; - fixedBody.appendChild(fixedBase); - - var isDevice = false; - var deviceWidth = 0; - var updateHtmlWidth = function (panelWidthOffset, scale, height, scaleN) { - var iosSafHtml = $('#ios-safari-html'); - iosSafHtml.css('overflow', ''); - iosSafHtml.css('overflow-x', ''); - iosSafHtml.css('height', ''); - if (isDevice) { - iosSafHtml.width(deviceWidth / scaleN); - iosSafHtml.css('overflow-x', 'hidden'); - } else { - var isLandscape = window.orientation != 0 && window.orientation != 180; - var mobileWidth = isLandscape ? window.screen.height : window.screen.width - iosSafHtml.width((mobileWidth - panelWidthOffset) / scaleN); - } - if (scale == 1) { - iosSafHtml.css('overflow-x', 'hidden'); - iosSafHtml.css('height', (height / scaleN) + 'px'); - } else if (scale == 2) iosSafHtml.css('overflow', 'hidden'); - }; - - updateHtmlWidth(0); - - $axure('*').each(function (obj, element) { - if (obj && obj.fixedVertical && obj.fixedKeepInFront) { - var parent = $axure('#' + element).getParents(false, ['item', 'state'])[0]; - if (!parent) { - $('#base-fixed').append($('#' + element)); - } - } - }); - - $axure.messageCenter.addMessageListener(function (message, data) { - if (message == "setContentScale") { - updateHtmlWidth(data.panelWidthOffset, data.scale, data.viewportHeight, data.scaleN); - } else if (message == "setDeviceMode") { - isDevice = data.device && !data.scaleToWidth; - if (isDevice) deviceWidth = data.width; - updateHtmlWidth(0); - } - }); - - - $('#ios-safari-html').scroll(function () { - $axure.updateWindowInfo(); - }); - - var scrollStartY; - var maxScrollY - var touchStart; - $axure('*').each(function (obj, element) { - if (obj && obj.scrollbars && obj.scrollbars.toLowerCase() != 'none') { - if (obj.scrollbars == 'horizontalAsNeeded') return; - - $('#' + element).on('touchstart', function (e) { - touchStart = e.pageY; - var stateId = $ax.visibility.GetPanelState($('#' + element).attr('id')); - scrollStartY = $('#' + stateId).scrollTop(); - maxScrollY = $('#' + stateId)[0].scrollHeight - $('#' + stateId).height(); - }); - - $('#' + element).on('touchmove', function (e) { - if (maxScrollY <= 0) return false; - if (scrollStartY == 0 && e.pageY > touchStart) e.preventDefault(); - if (scrollStartY == maxScrollY && e.pageY < touchStart) e.preventDefault(); - }); - } - }); - } -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/jquery.nicescroll.min.js b/web/main/static/resources/scripts/axure/jquery.nicescroll.min.js deleted file mode 100644 index c863c67..0000000 --- a/web/main/static/resources/scripts/axure/jquery.nicescroll.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?module.exports=e(require("jquery")):e(jQuery)}(function(e){"use strict";var o=!1,t=!1,r=0,i=2e3,s=0,n=e,l=document,a=window,c=n(a),d=[];var u=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||!1,h=a.cancelAnimationFrame||a.webkitCancelAnimationFrame||a.mozCancelAnimationFrame||!1;if(u)a.cancelAnimationFrame||(h=function(e){});else{var p=0;u=function(e,o){var t=(new Date).getTime(),r=Math.max(0,16-(t-p)),i=a.setTimeout(function(){e(t+r)},r);return p=t+r,i},h=function(e){a.clearTimeout(e)}}var m,f,g,v=a.MutationObserver||a.WebKitMutationObserver||!1,w=Date.now||function(){return(new Date).getTime()},b={zindex:"auto",cursoropacitymin:0,cursoropacitymax:1,cursorcolor:"#424242",cursorwidth:"6px",cursorborder:"1px solid #fff",cursorborderradius:"5px",scrollspeed:40,mousescrollstep:27,touchbehavior:!1,emulatetouch:!1,hwacceleration:!0,usetransition:!0,boxzoom:!1,dblclickzoom:!0,gesturezoom:!0,grabcursorenabled:!0,autohidemode:!0,background:"",iframeautoresize:!0,cursorminheight:32,preservenativescrolling:!0,railoffset:!1,railhoffset:!1,bouncescroll:!0,spacebarenabled:!0,railpadding:{top:0,right:0,left:0,bottom:0},disableoutline:!0,horizrailenabled:!0,railalign:"right",railvalign:"bottom",enabletranslate3d:!0,enablemousewheel:!0,enablekeyboard:!0,smoothscroll:!0,sensitiverail:!0,enablemouselockapi:!0,cursorfixedheight:!1,directionlockdeadzone:6,hidecursordelay:400,nativeparentscrolling:!0,enablescrollonselection:!0,overflowx:!0,overflowy:!0,cursordragspeed:.3,rtlmode:"auto",cursordragontouch:!1,oneaxismousemode:"auto",scriptpath:(f=l.currentScript||!!(m=l.getElementsByTagName("script")).length&&m[m.length-1],g=f?f.src.split("?")[0]:"",g.split("/").length>0?g.split("/").slice(0,-1).join("/")+"/":""),preventmultitouchscrolling:!0,disablemutationobserver:!1,enableobserver:!0,scrollbarid:!1},y=!1,x=function(e,p){var m=this;this.version="3.7.6",this.name="nicescroll",this.me=p;var f=n("body"),g=this.opt={doc:f,win:!1};if(n.extend(g,b),g.snapbackspeed=80,e)for(var x in g)void 0!==e[x]&&(g[x]=e[x]);if(g.disablemutationobserver&&(v=!1),this.doc=g.doc,this.iddoc=this.doc&&this.doc[0]&&this.doc[0].id||"",this.ispage=/^BODY|HTML/.test(g.win?g.win[0].nodeName:this.doc[0].nodeName),this.haswrapper=!1!==g.win,this.win=g.win||(this.ispage?c:this.doc),this.docscroll=this.ispage&&!this.haswrapper?c:this.win,this.body=f,this.viewport=!1,this.isfixed=!1,this.iframe=!1,this.isiframe="IFRAME"==this.doc[0].nodeName&&"IFRAME"==this.win[0].nodeName,this.istextarea="TEXTAREA"==this.win[0].nodeName,this.forcescreen=!1,this.canshowonmouseevent="scroll"!=g.autohidemode,this.onmousedown=!1,this.onmouseup=!1,this.onmousemove=!1,this.onmousewheel=!1,this.onkeypress=!1,this.ongesturezoom=!1,this.onclick=!1,this.onscrollstart=!1,this.onscrollend=!1,this.onscrollcancel=!1,this.onzoomin=!1,this.onzoomout=!1,this.view=!1,this.page=!1,this.scroll={x:0,y:0},this.scrollratio={x:0,y:0},this.cursorheight=20,this.scrollvaluemax=0,"auto"==g.rtlmode){var z=this.win[0]==a?this.body:this.win,k=z.css("writing-mode")||z.css("-webkit-writing-mode")||z.css("-ms-writing-mode")||z.css("-moz-writing-mode");"horizontal-tb"==k||"lr-tb"==k||""===k?(this.isrtlmode="rtl"==z.css("direction"),this.isvertical=!1):(this.isrtlmode="vertical-rl"==k||"tb"==k||"tb-rl"==k||"rl-tb"==k,this.isvertical="vertical-rl"==k||"tb"==k||"tb-rl"==k)}else this.isrtlmode=!0===g.rtlmode,this.isvertical=!1;if(this.scrollrunning=!1,this.scrollmom=!1,this.observer=!1,this.observerremover=!1,this.observerbody=!1,!1!==g.scrollbarid)this.id=g.scrollbarid;else do{this.id="ascrail"+i++}while(l.getElementById(this.id));this.rail=!1,this.cursor=!1,this.cursorfreezed=!1,this.selectiondrag=!1,this.zoom=!1,this.zoomactive=!1,this.hasfocus=!1,this.hasmousefocus=!1,this.railslocked=!1,this.locked=!1,this.hidden=!1,this.cursoractive=!0,this.wheelprevented=!1,this.overflowx=g.overflowx,this.overflowy=g.overflowy,this.nativescrollingarea=!1,this.checkarea=0,this.events=[],this.saved={},this.delaylist={},this.synclist={},this.lastdeltax=0,this.lastdeltay=0,this.detected=function(){if(y)return y;var e=l.createElement("DIV"),o=e.style,t=navigator.userAgent,r=navigator.platform,i={};return i.haspointerlock="pointerLockElement"in l||"webkitPointerLockElement"in l||"mozPointerLockElement"in l,i.isopera="opera"in a,i.isopera12=i.isopera&&"getUserMedia"in navigator,i.isoperamini="[object OperaMini]"===Object.prototype.toString.call(a.operamini),i.isie="all"in l&&"attachEvent"in e&&!i.isopera,i.isieold=i.isie&&!("msInterpolationMode"in o),i.isie7=i.isie&&!i.isieold&&(!("documentMode"in l)||7===l.documentMode),i.isie8=i.isie&&"documentMode"in l&&8===l.documentMode,i.isie9=i.isie&&"performance"in a&&9===l.documentMode,i.isie10=i.isie&&"performance"in a&&10===l.documentMode,i.isie11="msRequestFullscreen"in e&&l.documentMode>=11,i.ismsedge="msCredentials"in a,i.ismozilla="MozAppearance"in o,i.iswebkit=!i.ismsedge&&"WebkitAppearance"in o,i.ischrome=i.iswebkit&&"chrome"in a,i.ischrome38=i.ischrome&&"touchAction"in o,i.ischrome22=!i.ischrome38&&i.ischrome&&i.haspointerlock,i.ischrome26=!i.ischrome38&&i.ischrome&&"transition"in o,i.cantouch="ontouchstart"in l.documentElement||"ontouchstart"in a,i.hasw3ctouch=!!a.PointerEvent&&(navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0),i.hasmstouch=!i.hasw3ctouch&&(a.MSPointerEvent||!1),i.ismac=/^mac$/i.test(r),i.isios=i.cantouch&&/iphone|ipad|ipod/i.test(r),i.isios4=i.isios&&!("seal"in Object),i.isios7=i.isios&&"webkitHidden"in l,i.isios8=i.isios&&"hidden"in l,i.isios10=i.isios&&a.Proxy,i.isandroid=/android/i.test(t),i.haseventlistener="addEventListener"in e,i.trstyle=!1,i.hastransform=!1,i.hastranslate3d=!1,i.transitionstyle=!1,i.hastransition=!1,i.transitionend=!1,i.trstyle="transform",i.hastransform="transform"in o||function(){for(var e=["msTransform","webkitTransform","MozTransform","OTransform"],t=0,r=e.length;t<r;t++)if(void 0!==o[e[t]]){i.trstyle=e[t];break}i.hastransform=!!i.trstyle}(),i.hastransform&&(o[i.trstyle]="translate3d(1px,2px,3px)",i.hastranslate3d=/translate3d/.test(o[i.trstyle])),i.transitionstyle="transition",i.prefixstyle="",i.transitionend="transitionend",i.hastransition="transition"in o||function(){i.transitionend=!1;for(var e=["webkitTransition","msTransition","MozTransition","OTransition","OTransition","KhtmlTransition"],t=["-webkit-","-ms-","-moz-","-o-","-o","-khtml-"],r=["webkitTransitionEnd","msTransitionEnd","transitionend","otransitionend","oTransitionEnd","KhtmlTransitionEnd"],s=0,n=e.length;s<n;s++)if(e[s]in o){i.transitionstyle=e[s],i.prefixstyle=t[s],i.transitionend=r[s];break}i.ischrome26&&(i.prefixstyle=t[1]),i.hastransition=i.transitionstyle}(),i.cursorgrabvalue=function(){var e=["grab","-webkit-grab","-moz-grab"];(i.ischrome&&!i.ischrome38||i.isie)&&(e=[]);for(var t=0,r=e.length;t<r;t++){var s=e[t];if(o.cursor=s,o.cursor==s)return s}return"url(https://cdnjs.cloudflare.com/ajax/libs/slider-pro/1.3.0/css/images/openhand.cur),n-resize"}(),i.hasmousecapture="setCapture"in e,i.hasMutationObserver=!1!==v,e=null,y=i,i}();var T=n.extend({},this.detected);this.canhwscroll=T.hastransform&&g.hwacceleration,this.ishwscroll=this.canhwscroll&&m.haswrapper,this.isrtlmode?this.isvertical?this.hasreversehr=!(T.iswebkit||T.isie||T.isie11):this.hasreversehr=!(T.iswebkit||T.isie&&!T.isie10&&!T.isie11):this.hasreversehr=!1,this.istouchcapable=!1,(T.cantouch||!T.hasw3ctouch&&!T.hasmstouch)&&(!T.cantouch||T.isios||T.isandroid||!T.iswebkit&&!T.ismozilla)||(this.istouchcapable=!0),g.enablemouselockapi||(T.hasmousecapture=!1,T.haspointerlock=!1),this.debounced=function(e,o,t){m&&(m.delaylist[e]||!1||(m.delaylist[e]={h:u(function(){m.delaylist[e].fn.call(m),m.delaylist[e]=!1},t)},o.call(m)),m.delaylist[e].fn=o)},this.synched=function(e,o){m.synclist[e]?m.synclist[e]=o:(m.synclist[e]=o,u(function(){m&&(m.synclist[e]&&m.synclist[e].call(m),m.synclist[e]=null)}))},this.unsynched=function(e){m.synclist[e]&&(m.synclist[e]=!1)},this.css=function(e,o){for(var t in o)m.saved.css.push([e,t,e.css(t)]),e.css(t,o[t])},this.scrollTop=function(e){return void 0===e?m.getScrollTop():m.setScrollTop(e)},this.scrollLeft=function(e){return void 0===e?m.getScrollLeft():m.setScrollLeft(e)};var E=function(e,o,t,r,i,s,n){this.st=e,this.ed=o,this.spd=t,this.p1=r||0,this.p2=i||1,this.p3=s||0,this.p4=n||1,this.ts=w(),this.df=o-e};function M(){var e=m.doc.css(T.trstyle);return!(!e||"matrix"!=e.substr(0,6))&&e.replace(/^.*\((.*)\)$/g,"$1").replace(/px/g,"").split(/, +/)}if(E.prototype={B2:function(e){return 3*(1-e)*(1-e)*e},B3:function(e){return 3*(1-e)*e*e},B4:function(e){return e*e*e},getPos:function(){return(w()-this.ts)/this.spd},getNow:function(){var e=(w()-this.ts)/this.spd,o=this.B2(e)+this.B3(e)+this.B4(e);return e>=1?this.ed:this.st+this.df*o|0},update:function(e,o){return this.st=this.getNow(),this.ed=e,this.spd=o,this.ts=w(),this.df=this.ed-this.st,this}},this.ishwscroll){this.doc.translate={x:0,y:0,tx:"0px",ty:"0px"},T.hastranslate3d&&T.isios&&this.doc.css("-webkit-backface-visibility","hidden"),this.getScrollTop=function(e){if(!e){var o=M();if(o)return 16==o.length?-o[13]:-o[5];if(m.timerscroll&&m.timerscroll.bz)return m.timerscroll.bz.getNow()}return m.doc.translate.y},this.getScrollLeft=function(e){if(!e){var o=M();if(o)return 16==o.length?-o[12]:-o[4];if(m.timerscroll&&m.timerscroll.bh)return m.timerscroll.bh.getNow()}return m.doc.translate.x},this.notifyScrollEvent=function(e){var o=l.createEvent("UIEvents");o.initUIEvent("scroll",!1,!1,a,1),o.niceevent=!0,e.dispatchEvent(o)};var L=this.isrtlmode?1:-1;T.hastranslate3d&&g.enabletranslate3d?(this.setScrollTop=function(e,o){m.doc.translate.y=e,m.doc.translate.ty=-1*e+"px",m.doc.css(T.trstyle,"translate3d("+m.doc.translate.tx+","+m.doc.translate.ty+",0)"),o||m.notifyScrollEvent(m.win[0])},this.setScrollLeft=function(e,o){m.doc.translate.x=e,m.doc.translate.tx=e*L+"px",m.doc.css(T.trstyle,"translate3d("+m.doc.translate.tx+","+m.doc.translate.ty+",0)"),o||m.notifyScrollEvent(m.win[0])}):(this.setScrollTop=function(e,o){m.doc.translate.y=e,m.doc.translate.ty=-1*e+"px",m.doc.css(T.trstyle,"translate("+m.doc.translate.tx+","+m.doc.translate.ty+")"),o||m.notifyScrollEvent(m.win[0])},this.setScrollLeft=function(e,o){m.doc.translate.x=e,m.doc.translate.tx=e*L+"px",m.doc.css(T.trstyle,"translate("+m.doc.translate.tx+","+m.doc.translate.ty+")"),o||m.notifyScrollEvent(m.win[0])})}else this.getScrollTop=function(){return m.docscroll.scrollTop()},this.setScrollTop=function(e){m.docscroll.scrollTop(e)},this.getScrollLeft=function(){return m.hasreversehr?m.detected.ismozilla?m.page.maxw-Math.abs(m.docscroll.scrollLeft()):m.page.maxw-m.docscroll.scrollLeft():m.docscroll.scrollLeft()},this.setScrollLeft=function(e){return setTimeout(function(){if(m)return m.hasreversehr&&(e=m.detected.ismozilla?-(m.page.maxw-e):m.page.maxw-e),m.docscroll.scrollLeft(e)},1)};this.getTarget=function(e){return!!e&&(e.target?e.target:!!e.srcElement&&e.srcElement)},this.hasParent=function(e,o){if(!e)return!1;for(var t=e.target||e.srcElement||e||!1;t&&t.id!=o;)t=t.parentNode||!1;return!1!==t};var C={thin:1,medium:3,thick:5};function N(e,o,t){var r=e.css(o),i=parseFloat(r);if(isNaN(i)){var s=3==(i=C[r]||0)?t?m.win.outerHeight()-m.win.innerHeight():m.win.outerWidth()-m.win.innerWidth():1;return m.isie8&&i&&(i+=1),s?i:0}return i}this.getDocumentScrollOffset=function(){return{top:a.pageYOffset||l.documentElement.scrollTop,left:a.pageXOffset||l.documentElement.scrollLeft}},this.getOffset=function(){if(m.isfixed){var e=m.win.offset(),o=m.getDocumentScrollOffset();return e.top-=o.top,e.left-=o.left,e}var t=m.win.offset();if(!m.viewport)return t;var r=m.viewport.offset();return{top:t.top-r.top,left:t.left-r.left}},this.updateScrollBar=function(e){var o,t;if(m.ishwscroll)m.rail.css({height:m.win.innerHeight()-(g.railpadding.top+g.railpadding.bottom)}),m.railh&&m.railh.css({width:m.win.innerWidth()-(g.railpadding.left+g.railpadding.right)});else{var r=m.getOffset();if((o={top:r.top,left:r.left-(g.railpadding.left+g.railpadding.right)}).top+=N(m.win,"border-top-width",!0),o.left+=m.rail.align?m.win.outerWidth()-N(m.win,"border-right-width")-m.rail.width:N(m.win,"border-left-width"),(t=g.railoffset)&&(t.top&&(o.top+=t.top),t.left&&(o.left+=t.left)),m.railslocked||m.rail.css({top:o.top,left:o.left,height:(e?e.h:m.win.innerHeight())-(g.railpadding.top+g.railpadding.bottom)}),m.zoom&&m.zoom.css({top:o.top+1,left:1==m.rail.align?o.left-20:o.left+m.rail.width+4}),m.railh&&!m.railslocked){o={top:r.top,left:r.left},(t=g.railhoffset)&&(t.top&&(o.top+=t.top),t.left&&(o.left+=t.left));var i=m.railh.align?o.top+N(m.win,"border-top-width",!0)+m.win.innerHeight()-m.railh.height:o.top+N(m.win,"border-top-width",!0),s=o.left+N(m.win,"border-left-width");m.railh.css({top:i-(g.railpadding.top+g.railpadding.bottom),left:s,width:m.railh.width})}}},this.doRailClick=function(e,o,t){var r,i,s,n;m.railslocked||(m.cancelEvent(e),"pageY"in e||(e.pageX=e.clientX+l.documentElement.scrollLeft,e.pageY=e.clientY+l.documentElement.scrollTop),o?(r=t?m.doScrollLeft:m.doScrollTop,s=t?(e.pageX-m.railh.offset().left-m.cursorwidth/2)*m.scrollratio.x:(e.pageY-m.rail.offset().top-m.cursorheight/2)*m.scrollratio.y,m.unsynched("relativexy"),r(0|s)):(r=t?m.doScrollLeftBy:m.doScrollBy,s=t?m.scroll.x:m.scroll.y,n=t?e.pageX-m.railh.offset().left:e.pageY-m.rail.offset().top,i=t?m.view.w:m.view.h,r(s>=n?i:-i)))},m.newscrolly=m.newscrollx=0,m.hasanimationframe="requestAnimationFrame"in a,m.hascancelanimationframe="cancelAnimationFrame"in a,m.hasborderbox=!1,this.init=function(){if(m.saved.css=[],T.isoperamini)return!0;if(T.isandroid&&!("hidden"in l))return!0;g.emulatetouch=g.emulatetouch||g.touchbehavior,m.hasborderbox=a.getComputedStyle&&"border-box"===a.getComputedStyle(l.body)["box-sizing"];var e={"overflow-y":"hidden"};if((T.isie11||T.isie10)&&(e["-ms-overflow-style"]="none"),m.ishwscroll&&(this.doc.css(T.transitionstyle,T.prefixstyle+"transform 0ms ease-out"),T.transitionend&&m.bind(m.doc,T.transitionend,m.onScrollTransitionEnd,!1)),m.zindex="auto",m.ispage||"auto"!=g.zindex?m.zindex=g.zindex:m.zindex=function(){var e=m.win;if("zIndex"in e)return e.zIndex();for(;e.length>0;){if(9==e[0].nodeType)return!1;var o=e.css("zIndex");if(!isNaN(o)&&0!==o)return parseInt(o);e=e.parent()}return!1}()||"auto",!m.ispage&&"auto"!=m.zindex&&m.zindex>s&&(s=m.zindex),m.isie&&0===m.zindex&&"auto"==g.zindex&&(m.zindex="auto"),!m.ispage||!T.isieold){var i=m.docscroll;m.ispage&&(i=m.haswrapper?m.win:m.doc),m.css(i,e),m.ispage&&(T.isie11||T.isie)&&m.css(n("html"),e),!T.isios||m.ispage||m.haswrapper||m.css(f,{"-webkit-overflow-scrolling":"touch"});var d=n(l.createElement("div"));d.css({position:"relative",top:0,float:"right",width:g.cursorwidth,height:0,"background-color":g.cursorcolor,border:g.cursorborder,"background-clip":"padding-box","-webkit-border-radius":g.cursorborderradius,"-moz-border-radius":g.cursorborderradius,"border-radius":g.cursorborderradius}),d.addClass("nicescroll-cursors"),m.cursor=d;var u=n(l.createElement("div"));u.attr("id",m.id),u.addClass("nicescroll-rails nicescroll-rails-vr");var h,p,w=["left","right","top","bottom"];for(var b in w)p=w[b],(h=g.railpadding[p]||0)&&u.css("padding-"+p,h+"px");u.append(d),u.width=Math.max(parseFloat(g.cursorwidth),d.outerWidth()),u.css({width:u.width+"px",zIndex:m.zindex,background:g.background,cursor:"default"}),u.visibility=!0,u.scrollable=!0,u.align="left"==g.railalign?0:1,m.rail=u,m.rail.drag=!1;var y,x=!1;if(!g.boxzoom||m.ispage||T.isieold||(x=l.createElement("div"),m.bind(x,"click",m.doZoom),m.bind(x,"mouseenter",function(){m.zoom.css("opacity",g.cursoropacitymax)}),m.bind(x,"mouseleave",function(){m.zoom.css("opacity",g.cursoropacitymin)}),m.zoom=n(x),m.zoom.css({cursor:"pointer",zIndex:m.zindex,backgroundImage:"url("+g.scriptpath+"zoomico.png)",height:18,width:18,backgroundPosition:"0 0"}),g.dblclickzoom&&m.bind(m.win,"dblclick",m.doZoom),T.cantouch&&g.gesturezoom&&(m.ongesturezoom=function(e){return e.scale>1.5&&m.doZoomIn(e),e.scale<.8&&m.doZoomOut(e),m.cancelEvent(e)},m.bind(m.win,"gestureend",m.ongesturezoom))),m.railh=!1,g.horizrailenabled&&(m.css(i,{overflowX:"hidden"}),(d=n(l.createElement("div"))).css({position:"absolute",top:0,height:g.cursorwidth,width:0,backgroundColor:g.cursorcolor,border:g.cursorborder,backgroundClip:"padding-box","-webkit-border-radius":g.cursorborderradius,"-moz-border-radius":g.cursorborderradius,"border-radius":g.cursorborderradius}),T.isieold&&d.css("overflow","hidden"),d.addClass("nicescroll-cursors"),m.cursorh=d,(y=n(l.createElement("div"))).attr("id",m.id+"-hr"),y.addClass("nicescroll-rails nicescroll-rails-hr"),y.height=Math.max(parseFloat(g.cursorwidth),d.outerHeight()),y.css({height:y.height+"px",zIndex:m.zindex,background:g.background}),y.append(d),y.visibility=!0,y.scrollable=!0,y.align="top"==g.railvalign?0:1,m.railh=y,m.railh.drag=!1),m.ispage)u.css({position:"fixed",top:0,height:"100%"}),u.css(u.align?{right:0}:{left:0}),m.body.append(u),m.railh&&(y.css({position:"fixed",left:0,width:"100%"}),y.css(y.align?{bottom:0}:{top:0}),m.body.append(y));else{if(m.ishwscroll){"static"==m.win.css("position")&&m.css(m.win,{position:"relative"});var z="HTML"==m.win[0].nodeName?m.body:m.win;n(z).scrollTop(0).scrollLeft(0),m.zoom&&(m.zoom.css({position:"absolute",top:1,right:0,"margin-right":u.width+4}),z.append(m.zoom)),u.css({position:"absolute",top:0}),u.css(u.align?{right:0}:{left:0}),z.append(u),y&&(y.css({position:"absolute",left:0,bottom:0}),y.css(y.align?{bottom:0}:{top:0}),z.append(y))}else{m.isfixed="fixed"==m.win.css("position");var k=m.isfixed?"fixed":"absolute";m.isfixed||(m.viewport=m.getViewport(m.win[0])),m.viewport&&(m.body=m.viewport,/fixed|absolute/.test(m.viewport.css("position"))||m.css(m.viewport,{position:"relative"})),u.css({position:k}),m.zoom&&m.zoom.css({position:k}),m.updateScrollBar(),m.body.append(u),m.zoom&&m.body.append(m.zoom),m.railh&&(y.css({position:k}),m.body.append(y))}T.isios&&m.css(m.win,{"-webkit-tap-highlight-color":"rgba(0,0,0,0)","-webkit-touch-callout":"none"}),g.disableoutline&&(T.isie&&m.win.attr("hideFocus","true"),T.iswebkit&&m.win.css("outline","none"))}if(!1===g.autohidemode?(m.autohidedom=!1,m.rail.css({opacity:g.cursoropacitymax}),m.railh&&m.railh.css({opacity:g.cursoropacitymax})):!0===g.autohidemode||"leave"===g.autohidemode?(m.autohidedom=n().add(m.rail),T.isie8&&(m.autohidedom=m.autohidedom.add(m.cursor)),m.railh&&(m.autohidedom=m.autohidedom.add(m.railh)),m.railh&&T.isie8&&(m.autohidedom=m.autohidedom.add(m.cursorh))):"scroll"==g.autohidemode?(m.autohidedom=n().add(m.rail),m.railh&&(m.autohidedom=m.autohidedom.add(m.railh))):"cursor"==g.autohidemode?(m.autohidedom=n().add(m.cursor),m.railh&&(m.autohidedom=m.autohidedom.add(m.cursorh))):"hidden"==g.autohidemode&&(m.autohidedom=!1,m.hide(),m.railslocked=!1),T.cantouch||m.istouchcapable||g.emulatetouch||T.hasmstouch){m.scrollmom=new S(m);m.ontouchstart=function(e){if(m.locked)return!1;if(e.pointerType&&("mouse"===e.pointerType||e.pointerType===e.MSPOINTER_TYPE_MOUSE))return!1;if(m.hasmoving=!1,m.scrollmom.timer&&(m.triggerScrollEnd(),m.scrollmom.stop()),!m.railslocked){var o=m.getTarget(e);if(o)if(/INPUT/i.test(o.nodeName)&&/range/i.test(o.type))return m.stopPropagation(e);var t="mousedown"===e.type;if(!("clientX"in e)&&"changedTouches"in e&&(e.clientX=e.changedTouches[0].clientX,e.clientY=e.changedTouches[0].clientY),m.forcescreen){var r=e;(e={original:e.original?e.original:e}).clientX=r.screenX,e.clientY=r.screenY}if(g.horizrailenabled?m.rail.drag={x:e.clientX,y:e.clientY,sx:m.scroll.x,sy:m.scroll.y,st:m.getScrollTop(),sl:m.getScrollLeft(),pt:2,dl:!1,tg:o}:m.rail.drag={x:0,y:e.clientY,sx:0,sy:m.scroll.y,st:m.getScrollTop(),sl:0,pt:2,dl:!1,tg:o},m.ispage||!g.directionlockdeadzone)m.rail.drag.dl="f";else{var i=c.width(),s=c.height(),l=m.getContentSize(),a=l.h-s,d=l.w-i;m.rail.scrollable&&!m.railh.scrollable?m.rail.drag.ck=a>0&&"v":!m.rail.scrollable&&m.railh.scrollable?m.rail.drag.ck=d>0&&"h":m.rail.drag.ck=!1}if(g.emulatetouch&&m.isiframe&&T.isie){var u=m.win.position();m.rail.drag.x+=u.left,m.rail.drag.y+=u.top}if(m.hasmoving=!1,m.lastmouseup=!1,g.horizrailenabled?m.scrollmom.reset(e.clientX,e.clientY):m.scrollmom.reset(0,e.clientY),o&&t){if(!/INPUT|SELECT|BUTTON|TEXTAREA/i.test(o.nodeName))return T.hasmousecapture&&o.setCapture(),g.emulatetouch?(o.onclick&&!o._onclick&&(o._onclick=o.onclick,o.onclick=function(e){if(m.hasmoving)return!1;o._onclick.call(this,e)}),m.cancelEvent(e)):m.stopPropagation(e);/SUBMIT|CANCEL|BUTTON/i.test(n(o).attr("type"))&&(m.preventclick={tg:o,click:!1})}}},m.ontouchend=function(e){if(!m.rail.drag)return!0;if(2==m.rail.drag.pt){if(e.pointerType&&("mouse"===e.pointerType||e.pointerType===e.MSPOINTER_TYPE_MOUSE))return!1;m.rail.drag=!1;var o="mouseup"===e.type;if(m.hasmoving&&(m.scrollmom.doMomentum(),m.lastmouseup=!0,m.hideCursor(),T.hasmousecapture&&l.releaseCapture(),o))return m.cancelEvent(e)}else if(1==m.rail.drag.pt)return m.onmouseup(e)};var E=g.emulatetouch&&m.isiframe&&!T.hasmousecapture,M=.3*g.directionlockdeadzone|0;m.ontouchmove=function(e,o){if(!m.rail.drag)return!0;if(e.targetTouches&&g.preventmultitouchscrolling&&e.targetTouches.length>1)return!0;if(e.pointerType&&("mouse"===e.pointerType||e.pointerType===e.MSPOINTER_TYPE_MOUSE))return!0;if(2==m.rail.drag.pt){var t,r;if("changedTouches"in e&&(e.clientX=e.changedTouches[0].clientX,e.clientY=e.changedTouches[0].clientY),r=t=0,E&&!o){var i=m.win.position();r=-i.left,t=-i.top}var s=e.clientY+t,n=s-m.rail.drag.y,a=e.clientX+r;g.horizrailenabled||(a=0+r);var c=a-m.rail.drag.x,d=m.rail.drag.st-n;if(m.ishwscroll&&g.bouncescroll)d<0?d=Math.round(d/2):d>m.page.maxh&&(d=m.page.maxh+Math.round((d-m.page.maxh)/2));else if(d<0?(d=0,s=0):d>m.page.maxh&&(d=m.page.maxh,s=0),0===s&&!m.hasmoving)return m.ispage||(m.rail.drag=!1),!0;var u=m.getScrollLeft();if(m.railh&&m.railh.scrollable&&(u=m.isrtlmode?c-m.rail.drag.sl:m.rail.drag.sl-c,m.ishwscroll&&g.bouncescroll?u<0?u=Math.round(u/2):u>m.page.maxw&&(u=m.page.maxw+Math.round((u-m.page.maxw)/2)):(u<0&&(u=0,a=0),u>m.page.maxw&&(u=m.page.maxw,a=0))),!m.hasmoving){if(m.rail.drag.y===e.clientY&&m.rail.drag.x===e.clientX)return m.cancelEvent(e);var h=Math.abs(n),p=Math.abs(c),f=g.directionlockdeadzone;if(m.rail.drag.ck?"v"==m.rail.drag.ck?p>f&&h<=M?m.rail.drag=!1:h>f&&(m.rail.drag.dl="v"):"h"==m.rail.drag.ck&&(h>f&&p<=M?m.rail.drag=!1:p>f&&(m.rail.drag.dl="h")):h>f&&p>f?m.rail.drag.dl="f":h>f?m.rail.drag.dl=p>M?"f":"v":p>f&&(m.rail.drag.dl=h>M?"f":"h"),!m.rail.drag.dl)return m.cancelEvent(e);g.horizrailenabled?m.triggerScrollStart(e.clientX,e.clientY,0,0,0):m.triggerScrollStart(0,e.clientY,0,0,0),m.hasmoving=!0}return m.preventclick&&!m.preventclick.click&&(m.preventclick.click=m.preventclick.tg.onclick||!1,m.preventclick.tg.onclick=m.onpreventclick),m.rail.drag.dl&&("v"==m.rail.drag.dl?u=m.rail.drag.sl:"h"==m.rail.drag.dl&&(d=m.rail.drag.st)),m.synched("touchmove",function(){m.rail.drag&&2==m.rail.drag.pt&&(m.prepareTransition&&m.resetTransition(),m.rail.scrollable&&m.setScrollTop(d),m.scrollmom.update(a,s),m.railh&&m.railh.scrollable?(m.setScrollLeft(u),m.showCursor(d,u)):m.showCursor(d),T.isie10&&l.selection.clear())}),m.cancelEvent(e)}return 1==m.rail.drag.pt?m.onmousemove(e):void 0},m.ontouchstartCursor=function(e,o){if(!m.rail.drag||3==m.rail.drag.pt){if(m.locked)return m.cancelEvent(e);m.cancelScroll(),g.horizrailenabled?m.rail.drag={x:e.touches[0].clientX,y:e.touches[0].clientY,sx:m.scroll.x,sy:m.scroll.y,pt:3,hr:!!o}:m.rail.drag={x:0,y:e.touches[0].clientY,sx:0,sy:m.scroll.y,pt:3,hr:!!o};var t=m.getTarget(e);return!m.ispage&&T.hasmousecapture&&t.setCapture(),m.isiframe&&!T.hasmousecapture&&(m.saved.csspointerevents=m.doc.css("pointer-events"),m.css(m.doc,{"pointer-events":"none"})),m.cancelEvent(e)}},m.ontouchendCursor=function(e){if(m.rail.drag){if(T.hasmousecapture&&l.releaseCapture(),m.isiframe&&!T.hasmousecapture&&m.doc.css("pointer-events",m.saved.csspointerevents),3!=m.rail.drag.pt)return;return m.rail.drag=!1,m.cancelEvent(e)}},m.ontouchmoveCursor=function(e){if(m.rail.drag){if(3!=m.rail.drag.pt)return;if(m.cursorfreezed=!0,m.rail.drag.hr){if(g.horizrailenabled){m.scroll.x=m.rail.drag.sx+(e.touches[0].clientX-m.rail.drag.x),m.scroll.x<0&&(m.scroll.x=0);var o=m.scrollvaluemaxw;m.scroll.x>o&&(m.scroll.x=o)}}else{m.scroll.y=m.rail.drag.sy+(e.touches[0].clientY-m.rail.drag.y),m.scroll.y<0&&(m.scroll.y=0);var t=m.scrollvaluemax;m.scroll.y>t&&(m.scroll.y=t)}return m.synched("touchmove",function(){m.rail.drag&&3==m.rail.drag.pt&&(m.showCursor(),m.rail.drag.hr?m.doScrollLeft(Math.round(m.scroll.x*m.scrollratio.x),g.cursordragspeed):m.doScrollTop(Math.round(m.scroll.y*m.scrollratio.y),g.cursordragspeed))}),m.cancelEvent(e)}}}if(m.onmousedown=function(e,o){if(!m.rail.drag||1==m.rail.drag.pt){if(m.railslocked)return m.cancelEvent(e);m.cancelScroll(),g.horizrailenabled?m.rail.drag={x:e.clientX,y:e.clientY,sx:m.scroll.x,sy:m.scroll.y,pt:1,hr:o||!1}:m.rail.drag={x:0,y:e.clientY,sx:0,sy:m.scroll.y,pt:1,hr:o||!1};var t=m.getTarget(e);return T.hasmousecapture&&t.setCapture(),m.isiframe&&!T.hasmousecapture&&(m.saved.csspointerevents=m.doc.css("pointer-events"),m.css(m.doc,{"pointer-events":"none"})),m.hasmoving=!1,m.cancelEvent(e)}},m.onmouseup=function(e){if(m.rail.drag)return 1!=m.rail.drag.pt||(T.hasmousecapture&&l.releaseCapture(),m.isiframe&&!T.hasmousecapture&&m.doc.css("pointer-events",m.saved.csspointerevents),m.rail.drag=!1,m.cursorfreezed=!1,m.hasmoving&&m.triggerScrollEnd(),m.cancelEvent(e))},m.onmousemove=function(e){if(m.rail.drag){if(1!==m.rail.drag.pt)return;if(T.ischrome&&0===e.which)return m.onmouseup(e);if(m.cursorfreezed=!0,g.horizrailenabled?m.hasmoving||m.triggerScrollStart(e.clientX,e.clientY,0,0,0):m.hasmoving||m.triggerScrollStart(0,e.clientY,0,0,0),m.hasmoving=!0,m.rail.drag.hr){if(g.horizrailenabled){m.scroll.x=m.rail.drag.sx+(e.clientX-m.rail.drag.x),m.scroll.x<0&&(m.scroll.x=0);var o=m.scrollvaluemaxw;m.scroll.x>o&&(m.scroll.x=o)}}else{m.scroll.y=m.rail.drag.sy+(e.clientY-m.rail.drag.y),m.scroll.y<0&&(m.scroll.y=0);var t=m.scrollvaluemax;m.scroll.y>t&&(m.scroll.y=t)}return m.synched("mousemove",function(){m.cursorfreezed&&(m.showCursor(),m.rail.drag.hr?m.scrollLeft(Math.round(m.scroll.x*m.scrollratio.x)):m.scrollTop(Math.round(m.scroll.y*m.scrollratio.y)))}),m.cancelEvent(e)}m.checkarea=0},T.cantouch||g.emulatetouch)m.onpreventclick=function(e){if(m.preventclick)return m.preventclick.tg.onclick=m.preventclick.click,m.preventclick=!1,m.cancelEvent(e)},m.onclick=!T.isios&&function(e){return!m.lastmouseup||(m.lastmouseup=!1,m.cancelEvent(e))},g.grabcursorenabled&&T.cursorgrabvalue&&(m.css(m.ispage?m.doc:m.win,{cursor:T.cursorgrabvalue}),m.css(m.rail,{cursor:T.cursorgrabvalue}));else{var L=function(e){if(m.selectiondrag){if(e){var o=m.win.outerHeight(),t=e.pageY-m.selectiondrag.top;t>0&&t<o&&(t=0),t>=o&&(t-=o),m.selectiondrag.df=t}if(0!==m.selectiondrag.df){var r=-2*m.selectiondrag.df/6|0;m.doScrollBy(r),m.debounced("doselectionscroll",function(){L()},50)}}};m.hasTextSelected="getSelection"in l?function(){return l.getSelection().rangeCount>0}:"selection"in l?function(){return"None"!=l.selection.type}:function(){return!1},m.onselectionstart=function(e){m.ispage||(m.selectiondrag=m.win.offset())},m.onselectionend=function(e){m.selectiondrag=!1},m.onselectiondrag=function(e){m.selectiondrag&&m.hasTextSelected()&&m.debounced("selectionscroll",function(){L(e)},250)}}if(T.hasw3ctouch?(m.css(m.ispage?n("html"):m.win,{"touch-action":"none"}),m.css(m.rail,{"touch-action":"none"}),m.css(m.cursor,{"touch-action":"none"}),m.bind(m.win,"pointerdown",m.ontouchstart),m.bind(l,"pointerup",m.ontouchend),m.delegate(l,"pointermove",m.ontouchmove)):T.hasmstouch?(m.css(m.ispage?n("html"):m.win,{"-ms-touch-action":"none"}),m.css(m.rail,{"-ms-touch-action":"none"}),m.css(m.cursor,{"-ms-touch-action":"none"}),m.bind(m.win,"MSPointerDown",m.ontouchstart),m.bind(l,"MSPointerUp",m.ontouchend),m.delegate(l,"MSPointerMove",m.ontouchmove),m.bind(m.cursor,"MSGestureHold",function(e){e.preventDefault()}),m.bind(m.cursor,"contextmenu",function(e){e.preventDefault()})):T.cantouch&&(m.bind(m.win,"touchstart",m.ontouchstart,!1,!0),m.bind(l,"touchend",m.ontouchend,!1,!0),m.bind(l,"touchcancel",m.ontouchend,!1,!0),m.delegate(l,"touchmove",m.ontouchmove,!1,!0)),g.emulatetouch&&(m.bind(m.win,"mousedown",m.ontouchstart,!1,!0),m.bind(l,"mouseup",m.ontouchend,!1,!0),m.bind(l,"mousemove",m.ontouchmove,!1,!0)),(g.cursordragontouch||!T.cantouch&&!g.emulatetouch)&&(m.rail.css({cursor:"default"}),m.railh&&m.railh.css({cursor:"default"}),m.jqbind(m.rail,"mouseenter",function(){if(!m.ispage&&!m.win.is(":visible"))return!1;m.canshowonmouseevent&&m.showCursor(),m.rail.active=!0}),m.jqbind(m.rail,"mouseleave",function(){m.rail.active=!1,m.rail.drag||m.hideCursor()}),g.sensitiverail&&(m.bind(m.rail,"click",function(e){m.doRailClick(e,!1,!1)}),m.bind(m.rail,"dblclick",function(e){m.doRailClick(e,!0,!1)}),m.bind(m.cursor,"click",function(e){m.cancelEvent(e)}),m.bind(m.cursor,"dblclick",function(e){m.cancelEvent(e)})),m.railh&&(m.jqbind(m.railh,"mouseenter",function(){if(!m.ispage&&!m.win.is(":visible"))return!1;m.canshowonmouseevent&&m.showCursor(),m.rail.active=!0}),m.jqbind(m.railh,"mouseleave",function(){m.rail.active=!1,m.rail.drag||m.hideCursor()}),g.sensitiverail&&(m.bind(m.railh,"click",function(e){m.doRailClick(e,!1,!0)}),m.bind(m.railh,"dblclick",function(e){m.doRailClick(e,!0,!0)}),m.bind(m.cursorh,"click",function(e){m.cancelEvent(e)}),m.bind(m.cursorh,"dblclick",function(e){m.cancelEvent(e)})))),g.cursordragontouch&&(this.istouchcapable||T.cantouch)&&(m.bind(m.cursor,"touchstart",m.ontouchstartCursor),m.bind(m.cursor,"touchmove",m.ontouchmoveCursor),m.bind(m.cursor,"touchend",m.ontouchendCursor),m.cursorh&&m.bind(m.cursorh,"touchstart",function(e){m.ontouchstartCursor(e,!0)}),m.cursorh&&m.bind(m.cursorh,"touchmove",m.ontouchmoveCursor),m.cursorh&&m.bind(m.cursorh,"touchend",m.ontouchendCursor)),g.emulatetouch||T.isandroid||T.isios?(m.bind(T.hasmousecapture?m.win:l,"mouseup",m.ontouchend),m.onclick&&m.bind(l,"click",m.onclick),g.cursordragontouch?(m.bind(m.cursor,"mousedown",m.onmousedown),m.bind(m.cursor,"mouseup",m.onmouseup),m.cursorh&&m.bind(m.cursorh,"mousedown",function(e){m.onmousedown(e,!0)}),m.cursorh&&m.bind(m.cursorh,"mouseup",m.onmouseup)):(m.bind(m.rail,"mousedown",function(e){e.preventDefault()}),m.railh&&m.bind(m.railh,"mousedown",function(e){e.preventDefault()}))):(m.bind(T.hasmousecapture?m.win:l,"mouseup",m.onmouseup),m.bind(l,"mousemove",m.onmousemove),m.onclick&&m.bind(l,"click",m.onclick),m.bind(m.cursor,"mousedown",m.onmousedown),m.bind(m.cursor,"mouseup",m.onmouseup),m.railh&&(m.bind(m.cursorh,"mousedown",function(e){m.onmousedown(e,!0)}),m.bind(m.cursorh,"mouseup",m.onmouseup)),!m.ispage&&g.enablescrollonselection&&(m.bind(m.win[0],"mousedown",m.onselectionstart),m.bind(l,"mouseup",m.onselectionend),m.bind(m.cursor,"mouseup",m.onselectionend),m.cursorh&&m.bind(m.cursorh,"mouseup",m.onselectionend),m.bind(l,"mousemove",m.onselectiondrag)),m.zoom&&(m.jqbind(m.zoom,"mouseenter",function(){m.canshowonmouseevent&&m.showCursor(),m.rail.active=!0}),m.jqbind(m.zoom,"mouseleave",function(){m.rail.active=!1,m.rail.drag||m.hideCursor()}))),g.enablemousewheel&&(m.isiframe||m.mousewheel(T.isie&&m.ispage?l:m.win,m.onmousewheel),m.mousewheel(m.rail,m.onmousewheel),m.railh&&m.mousewheel(m.railh,m.onmousewheelhr)),m.ispage||T.cantouch||/HTML|^BODY/.test(m.win[0].nodeName)||(m.win.attr("tabindex")||m.win.attr({tabindex:++r}),m.bind(m.win,"focus",function(e){o=m.getTarget(e).id||m.getTarget(e)||!1,m.hasfocus=!0,m.canshowonmouseevent&&m.noticeCursor()}),m.bind(m.win,"blur",function(e){o=!1,m.hasfocus=!1}),m.bind(m.win,"mouseenter",function(e){t=m.getTarget(e).id||m.getTarget(e)||!1,m.hasmousefocus=!0,m.canshowonmouseevent&&m.noticeCursor()}),m.bind(m.win,"mouseleave",function(e){t=!1,m.hasmousefocus=!1,m.rail.drag||m.hideCursor()})),m.onkeypress=function(e){if(m.railslocked&&0===m.page.maxh)return!0;e=e||a.event;var r=m.getTarget(e);if(r&&/INPUT|TEXTAREA|SELECT|OPTION/.test(r.nodeName)&&(!(r.getAttribute("type")||r.type||!1)||!/submit|button|cancel/i.tp))return!0;if(n(r).attr("contenteditable"))return!0;if(m.hasfocus||m.hasmousefocus&&!o||m.ispage&&!o&&!t){var i=e.keyCode;if(m.railslocked&&27!=i)return m.cancelEvent(e);var s=e.ctrlKey||!1,l=e.shiftKey||!1,c=!1;switch(i){case 38:case 63233:m.doScrollBy(72),c=!0;break;case 40:case 63235:m.doScrollBy(-72),c=!0;break;case 37:case 63232:m.railh&&(s?m.doScrollLeft(0):m.doScrollLeftBy(72),c=!0);break;case 39:case 63234:m.railh&&(s?m.doScrollLeft(m.page.maxw):m.doScrollLeftBy(-72),c=!0);break;case 33:case 63276:m.doScrollBy(m.view.h),c=!0;break;case 34:case 63277:m.doScrollBy(-m.view.h),c=!0;break;case 36:case 63273:m.railh&&s?m.doScrollPos(0,0):m.doScrollTo(0),c=!0;break;case 35:case 63275:m.railh&&s?m.doScrollPos(m.page.maxw,m.page.maxh):m.doScrollTo(m.page.maxh),c=!0;break;case 32:g.spacebarenabled&&(l?m.doScrollBy(m.view.h):m.doScrollBy(-m.view.h),c=!0);break;case 27:m.zoomactive&&(m.doZoom(),c=!0)}if(c)return m.cancelEvent(e)}},g.enablekeyboard&&m.bind(l,T.isopera&&!T.isopera12?"keypress":"keydown",m.onkeypress),m.bind(l,"keydown",function(e){(e.ctrlKey||!1)&&(m.wheelprevented=!0)}),m.bind(l,"keyup",function(e){e.ctrlKey||!1||(m.wheelprevented=!1)}),m.bind(a,"blur",function(e){m.wheelprevented=!1}),m.bind(a,"resize",m.onscreenresize),m.bind(a,"orientationchange",m.onscreenresize),m.bind(a,"load",m.lazyResize),T.ischrome&&!m.ispage&&!m.haswrapper){var C=m.win.attr("style"),N=parseFloat(m.win.css("width"))+1;m.win.css("width",N),m.synched("chromefix",function(){m.win.attr("style",C)})}if(m.onAttributeChange=function(e){m.lazyResize(m.isieold?250:30)},g.enableobserver&&(m.isie11||!1===v||(m.observerbody=new v(function(e){if(e.forEach(function(e){if("attributes"==e.type)return f.hasClass("modal-open")&&f.hasClass("modal-dialog")&&!n.contains(n(".modal-dialog")[0],m.doc[0])?m.hide():m.show()}),m.me.clientWidth!=m.page.width||m.me.clientHeight!=m.page.height)return m.lazyResize(30)}),m.observerbody.observe(l.body,{childList:!0,subtree:!0,characterData:!1,attributes:!0,attributeFilter:["class"]})),!m.ispage&&!m.haswrapper)){var P=m.win[0];!1!==v?(m.observer=new v(function(e){e.forEach(m.onAttributeChange)}),m.observer.observe(P,{childList:!0,characterData:!1,attributes:!0,subtree:!1}),m.observerremover=new v(function(e){e.forEach(function(e){if(e.removedNodes.length>0)for(var o in e.removedNodes)if(m&&e.removedNodes[o]===P)return m.remove()})}),m.observerremover.observe(P.parentNode,{childList:!0,characterData:!1,attributes:!1,subtree:!1})):(m.bind(P,T.isie&&!T.isie9?"propertychange":"DOMAttrModified",m.onAttributeChange),T.isie9&&P.attachEvent("onpropertychange",m.onAttributeChange),m.bind(P,"DOMNodeRemoved",function(e){e.target===P&&m.remove()}))}!m.ispage&&g.boxzoom&&m.bind(a,"resize",m.resizeZoom),m.istextarea&&(m.bind(m.win,"keydown",m.lazyResize),m.bind(m.win,"mouseup",m.lazyResize)),m.lazyResize(30)}if("IFRAME"==this.doc[0].nodeName){var R=function(){var o;m.iframexd=!1;try{(o="contentDocument"in this?this.contentDocument:this.contentWindow._doc).domain}catch(e){m.iframexd=!0,o=!1}if(m.iframexd)return"console"in a&&console.log("NiceScroll error: policy restriced iframe"),!0;if(m.forcescreen=!0,m.isiframe&&(m.iframe={doc:n(o),html:m.doc.contents().find("html")[0],body:m.doc.contents().find("body")[0]},m.getContentSize=function(){return{w:Math.max(m.iframe.html.scrollWidth,m.iframe.body.scrollWidth),h:Math.max(m.iframe.html.scrollHeight,m.iframe.body.scrollHeight)}},m.docscroll=n(m.iframe.body)),!T.isios&&g.iframeautoresize&&!m.isiframe){m.win.scrollTop(0),m.doc.height("");var t=Math.max(o.getElementsByTagName("html")[0].scrollHeight,o.body.scrollHeight);m.doc.height(t)}m.lazyResize(30),m.css(n(m.iframe.body),e),T.isios&&m.haswrapper&&m.css(n(o.body),{"-webkit-transform":"translate3d(0,0,0)"}),"contentWindow"in this?m.bind(this.contentWindow,"scroll",m.onscroll):m.bind(o,"scroll",m.onscroll),g.enablemousewheel&&m.mousewheel(o,m.onmousewheel),g.enablekeyboard&&m.bind(o,T.isopera?"keypress":"keydown",m.onkeypress),T.cantouch?(m.bind(o,"touchstart",m.ontouchstart),m.bind(o,"touchmove",m.ontouchmove)):g.emulatetouch&&(m.bind(o,"mousedown",m.ontouchstart),m.bind(o,"mousemove",function(e){return m.ontouchmove(e,!0)}),g.grabcursorenabled&&T.cursorgrabvalue&&m.css(n(o.body),{cursor:T.cursorgrabvalue})),m.bind(o,"mouseup",m.ontouchend),m.zoom&&(g.dblclickzoom&&m.bind(o,"dblclick",m.doZoom),m.ongesturezoom&&m.bind(o,"gestureend",m.ongesturezoom))};this.doc[0].readyState&&"complete"===this.doc[0].readyState&&setTimeout(function(){R.call(m.doc[0],!1)},500),m.bind(this.doc,"load",R)}},this.showCursor=function(e,o){if(m.cursortimeout&&(clearTimeout(m.cursortimeout),m.cursortimeout=0),m.rail){if(m.autohidedom&&(m.autohidedom.stop().css({opacity:g.cursoropacitymax}),m.cursoractive=!0),m.rail.drag&&1==m.rail.drag.pt||(void 0!==e&&!1!==e&&(m.scroll.y=e/m.scrollratio.y|0),void 0!==o&&(m.scroll.x=o/m.scrollratio.x|0)),m.cursor.css({height:m.cursorheight,top:m.scroll.y}),m.cursorh){var t=m.hasreversehr?m.scrollvaluemaxw-m.scroll.x:m.scroll.x;m.cursorh.css({width:m.cursorwidth,left:!m.rail.align&&m.rail.visibility?t+m.rail.width:t}),m.cursoractive=!0}m.zoom&&m.zoom.stop().css({opacity:g.cursoropacitymax})}},this.hideCursor=function(e){m.cursortimeout||m.rail&&m.autohidedom&&(m.hasmousefocus&&"leave"===g.autohidemode||(m.cursortimeout=setTimeout(function(){m.rail.active&&m.showonmouseevent||(m.autohidedom.stop().animate({opacity:g.cursoropacitymin}),m.zoom&&m.zoom.stop().animate({opacity:g.cursoropacitymin}),m.cursoractive=!1),m.cursortimeout=0},e||g.hidecursordelay)))},this.noticeCursor=function(e,o,t){m.showCursor(o,t),m.rail.active||m.hideCursor(e)},this.getContentSize=m.ispage?function(){return{w:Math.max(l.body.scrollWidth,l.documentElement.scrollWidth),h:Math.max(l.body.scrollHeight,l.documentElement.scrollHeight)}}:m.haswrapper?function(){return{w:m.doc[0].offsetWidth,h:m.doc[0].offsetHeight}}:function(){return{w:m.docscroll[0].scrollWidth,h:m.docscroll[0].scrollHeight}},this.onResize=function(e,o){if(!m||!m.win)return!1;var t=m.page.maxh,r=m.page.maxw,i=m.view.h,s=m.view.w;if(m.view={w:m.ispage?m.win.width():m.win[0].clientWidth,h:m.ispage?m.win.height():m.win[0].clientHeight},m.page=o||m.getContentSize(),m.page.maxh=Math.max(0,m.page.h-m.view.h),m.page.maxw=Math.max(0,m.page.w-m.view.w),m.page.maxh==t&&m.page.maxw==r&&m.view.w==s&&m.view.h==i){if(m.ispage)return m;var n=m.win.offset();if(m.lastposition){var l=m.lastposition;if(l.top==n.top&&l.left==n.left)return m}m.lastposition=n}return 0===m.page.maxh?(m.hideRail(),m.scrollvaluemax=0,m.scroll.y=0,m.scrollratio.y=0,m.cursorheight=0,m.setScrollTop(0),m.rail&&(m.rail.scrollable=!1)):(m.page.maxh-=g.railpadding.top+g.railpadding.bottom,m.rail.scrollable=!0),0===m.page.maxw?(m.hideRailHr(),m.scrollvaluemaxw=0,m.scroll.x=0,m.scrollratio.x=0,m.cursorwidth=0,m.setScrollLeft(0),m.railh&&(m.railh.scrollable=!1)):(m.page.maxw-=g.railpadding.left+g.railpadding.right,m.railh&&(m.railh.scrollable=g.horizrailenabled)),m.railslocked=m.locked||0===m.page.maxh&&0===m.page.maxw,m.railslocked?(m.ispage||m.updateScrollBar(m.view),!1):(m.hidden||(m.rail.visibility||m.showRail(),m.railh&&!m.railh.visibility&&m.showRailHr()),m.istextarea&&m.win.css("resize")&&"none"!=m.win.css("resize")&&(m.view.h-=20),m.cursorheight=Math.min(m.view.h,Math.round(m.view.h*(m.view.h/m.page.h))),m.cursorheight=g.cursorfixedheight?g.cursorfixedheight:Math.max(g.cursorminheight,m.cursorheight),m.cursorwidth=Math.min(m.view.w,Math.round(m.view.w*(m.view.w/m.page.w))),m.cursorwidth=g.cursorfixedheight?g.cursorfixedheight:Math.max(g.cursorminheight,m.cursorwidth),m.scrollvaluemax=m.view.h-m.cursorheight-(g.railpadding.top+g.railpadding.bottom),m.hasborderbox||(m.scrollvaluemax-=m.cursor[0].offsetHeight-m.cursor[0].clientHeight),m.railh&&(m.railh.width=m.page.maxh>0?m.rail.width:m.view.w,m.scrollvaluemaxw=m.railh.width-m.cursorwidth-(g.railpadding.left+g.railpadding.right)),m.ispage||m.updateScrollBar(m.view),m.scrollratio={x:m.page.maxw/m.scrollvaluemaxw,y:m.page.maxh/m.scrollvaluemax},m.getScrollTop()>m.page.maxh?m.doScrollTop(m.page.maxh):(m.scroll.y=m.getScrollTop()/m.scrollratio.y|0,m.scroll.x=m.getScrollLeft()/m.scrollratio.x|0,m.cursoractive&&m.noticeCursor()),m.scroll.y&&0===m.getScrollTop()&&m.doScrollTo(m.scroll.y*m.scrollratio.y|0),m)},this.resize=m.onResize;var P=0;function R(e,o,t,r){m._bind(e,o,function(r){var i={original:r=r||a.event,target:r.target||r.srcElement,type:"wheel",deltaMode:"MozMousePixelScroll"==r.type?0:1,deltaX:0,deltaZ:0,preventDefault:function(){return r.preventDefault?r.preventDefault():r.returnValue=!1,!1},stopImmediatePropagation:function(){r.stopImmediatePropagation?r.stopImmediatePropagation():r.cancelBubble=!0}};return"mousewheel"==o?(r.wheelDeltaX&&(i.deltaX=-.025*r.wheelDeltaX),r.wheelDeltaY&&(i.deltaY=-.025*r.wheelDeltaY),!i.deltaY&&!i.deltaX&&(i.deltaY=-.025*r.wheelDelta)):i.deltaY=r.detail,t.call(e,i)},r)}this.onscreenresize=function(e){clearTimeout(P);var o=!m.ispage&&!m.haswrapper;o&&m.hideRails(),P=setTimeout(function(){m&&(o&&m.showRails(),m.resize()),P=0},120)},this.lazyResize=function(e){return clearTimeout(P),e=isNaN(e)?240:e,P=setTimeout(function(){m&&m.resize(),P=0},e),m},this.jqbind=function(e,o,t){m.events.push({e:e,n:o,f:t,q:!0}),n(e).on(o,t)},this.mousewheel=function(e,o,t){var r="jquery"in e?e[0]:e;if("onwheel"in l.createElement("div"))m._bind(r,"wheel",o,t||!1);else{var i=void 0!==l.onmousewheel?"mousewheel":"DOMMouseScroll";R(r,i,o,t||!1),"DOMMouseScroll"==i&&R(r,"MozMousePixelScroll",o,t||!1)}};var Y=!1;if(T.haseventlistener){try{var _=Object.defineProperty({},"passive",{get:function(){Y=!0}});a.addEventListener("test",null,_)}catch(e){}this.stopPropagation=function(e){return!!e&&((e=e.original?e.original:e).stopPropagation(),!1)},this.cancelEvent=function(e){return e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),e.preventManipulation&&e.preventManipulation(),!1}}else Event.prototype.preventDefault=function(){this.returnValue=!1},Event.prototype.stopPropagation=function(){this.cancelBubble=!0},a.constructor.prototype.addEventListener=l.constructor.prototype.addEventListener=Element.prototype.addEventListener=function(e,o,t){this.attachEvent("on"+e,o)},a.constructor.prototype.removeEventListener=l.constructor.prototype.removeEventListener=Element.prototype.removeEventListener=function(e,o,t){this.detachEvent("on"+e,o)},this.cancelEvent=function(e){return(e=e||a.event)&&(e.cancelBubble=!0,e.cancel=!0,e.returnValue=!1),!1},this.stopPropagation=function(e){return(e=e||a.event)&&(e.cancelBubble=!0),!1};this.delegate=function(e,o,t,r,i){var s=d[o]||!1;s||(s={a:[],l:[],f:function(e){for(var o=s.l,t=!1,r=o.length-1;r>=0;r--)if(!1===(t=o[r].call(e.target,e)))return!1;return t}},m.bind(e,o,s.f,r,i),d[o]=s),m.ispage?(s.a=[m.id].concat(s.a),s.l=[t].concat(s.l)):(s.a.push(m.id),s.l.push(t))},this.undelegate=function(e,o,t,r,i){var s=d[o]||!1;if(s&&s.l)for(var n=0,l=s.l.length;n<l;n++)s.a[n]===m.id&&(s.a.splice(n),s.l.splice(n),0===s.a.length&&(m._unbind(e,o,s.l.f),d[o]=null))},this.bind=function(e,o,t,r,i){var s="jquery"in e?e[0]:e;m._bind(s,o,t,r||!1,i||!1)},this._bind=function(e,o,t,r,i){m.events.push({e:e,n:o,f:t,b:r,q:!1}),Y&&(i||e==l||e==l.body||e==a)?e.addEventListener(o,t,{passive:!1,capture:r}):e.addEventListener(o,t,r||!1)},this._unbind=function(e,o,t,r){d[o]?m.undelegate(e,o,t,r):e.removeEventListener(o,t,r)},this.unbindAll=function(){for(var e=0;e<m.events.length;e++){var o=m.events[e];o.q?o.e.unbind(o.n,o.f):m._unbind(o.e,o.n,o.f,o.b)}},this.showRails=function(){return m.showRail().showRailHr()},this.showRail=function(){return 0===m.page.maxh||!m.ispage&&"none"==m.win.css("display")||(m.rail.visibility=!0,m.rail.css("display","block")),m},this.showRailHr=function(){return m.railh&&(0===m.page.maxw||!m.ispage&&"none"==m.win.css("display")||(m.railh.visibility=!0,m.railh.css("display","block"))),m},this.hideRails=function(){return m.hideRail().hideRailHr()},this.hideRail=function(){return m.rail.visibility=!1,m.rail.css("display","none"),m},this.hideRailHr=function(){return m.railh&&(m.railh.visibility=!1,m.railh.css("display","none")),m},this.show=function(){return m.hidden=!1,m.railslocked=!1,m.showRails()},this.hide=function(){return m.hidden=!0,m.railslocked=!0,m.hideRails()},this.toggle=function(){return m.hidden?m.show():m.hide()},this.remove=function(){m.stop(),m.cursortimeout&&clearTimeout(m.cursortimeout);for(var e in m.delaylist)m.delaylist[e]&&h(m.delaylist[e].h);m.doZoomOut(),m.unbindAll(),T.isie9&&m.win[0].detachEvent("onpropertychange",m.onAttributeChange),!1!==m.observer&&m.observer.disconnect(),!1!==m.observerremover&&m.observerremover.disconnect(),!1!==m.observerbody&&m.observerbody.disconnect(),m.events=null,m.cursor&&m.cursor.remove(),m.cursorh&&m.cursorh.remove(),m.rail&&m.rail.remove(),m.railh&&m.railh.remove(),m.zoom&&m.zoom.remove();for(var o=0;o<m.saved.css.length;o++){var t=m.saved.css[o];t[0].css(t[1],void 0===t[2]?"":t[2])}m.saved=!1,m.me.data("__nicescroll","");var r=n.nicescroll;r.each(function(e){if(this&&this.id===m.id){delete r[e];for(var o=++e;o<r.length;o++,e++)r[e]=r[o];r.length--,r.length&&delete r[r.length]}});for(var i in m)m[i]=null,delete m[i];m=null},this.scrollstart=function(e){return this.onscrollstart=e,m},this.scrollend=function(e){return this.onscrollend=e,m},this.scrollcancel=function(e){return this.onscrollcancel=e,m},this.zoomin=function(e){return this.onzoomin=e,m},this.zoomout=function(e){return this.onzoomout=e,m},this.isScrollable=function(e){var o=e.target?e.target:e;if("OPTION"==o.nodeName)return!0;for(;o&&1==o.nodeType&&o!==this.me[0]&&!/^BODY|HTML/.test(o.nodeName);){var t=n(o),r=t.css("overflowY")||t.css("overflowX")||t.css("overflow")||"";if(/scroll|auto/.test(r))return o.clientHeight!=o.scrollHeight;o=!!o.parentNode&&o.parentNode}return!1},this.getViewport=function(e){for(var o=!(!e||!e.parentNode)&&e.parentNode;o&&1==o.nodeType&&!/^BODY|HTML/.test(o.nodeName);){var t=n(o);if(/fixed|absolute/.test(t.css("position")))return t;var r=t.css("overflowY")||t.css("overflowX")||t.css("overflow")||"";if(/scroll|auto/.test(r)&&o.clientHeight!=o.scrollHeight)return t;if(t.getNiceScroll().length>0)return t;o=!!o.parentNode&&o.parentNode}return!1},this.triggerScrollStart=function(e,o,t,r,i){if(m.onscrollstart){var s={type:"scrollstart",current:{x:e,y:o},request:{x:t,y:r},end:{x:m.newscrollx,y:m.newscrolly},speed:i};m.onscrollstart.call(m,s)}},this.triggerScrollEnd=function(){if(m.onscrollend){var e=m.getScrollLeft(),o=m.getScrollTop(),t={type:"scrollend",current:{x:e,y:o},end:{x:e,y:o}};m.onscrollend.call(m,t)}};var I=0,O=0,H=0,B=1;function X(e,o,t,r){m.scrollrunning||(m.newscrolly=m.getScrollTop(),m.newscrollx=m.getScrollLeft(),H=w());var i=w()-H;if(H=w(),i>350?B=1:B+=(2-B)/10,o=o*B|0,e=e*B|0){if(r)if(e<0){if(m.getScrollLeft()>=m.page.maxw)return!0}else if(m.getScrollLeft()<=0)return!0;var s=e>0?1:-1;O!==s&&(m.scrollmom&&m.scrollmom.stop(),m.newscrollx=m.getScrollLeft(),O=s),m.lastdeltax-=e}if(o){if(function(){var e=m.getScrollTop();if(o<0){if(e>=m.page.maxh)return!0}else if(e<=0)return!0}()){if(g.nativeparentscrolling&&t&&!m.ispage&&!m.zoomactive)return!0;var n=m.view.h>>1;m.newscrolly<-n?(m.newscrolly=-n,o=-1):m.newscrolly>m.page.maxh+n?(m.newscrolly=m.page.maxh+n,o=1):o=0}var l=o>0?1:-1;I!==l&&(m.scrollmom&&m.scrollmom.stop(),m.newscrolly=m.getScrollTop(),I=l),m.lastdeltay-=o}(o||e)&&m.synched("relativexy",function(){var e=m.lastdeltay+m.newscrolly;m.lastdeltay=0;var o=m.lastdeltax+m.newscrollx;m.lastdeltax=0,m.rail.drag||m.doScrollPos(o,e)})}var D=!1;function A(e,o,t){var r,i;if(!t&&D)return!0;(0===e.deltaMode?(r=-e.deltaX*(g.mousescrollstep/54)|0,i=-e.deltaY*(g.mousescrollstep/54)|0):1===e.deltaMode&&(r=-e.deltaX*g.mousescrollstep*50/80|0,i=-e.deltaY*g.mousescrollstep*50/80|0),o&&g.oneaxismousemode&&0===r&&i)&&(r=i,i=0,t&&(r<0?m.getScrollLeft()>=m.page.maxw:m.getScrollLeft()<=0)&&(i=r,r=0));if(m.isrtlmode&&(r=-r),!X(r,i,t,!0))return D=!1,e.stopImmediatePropagation(),e.preventDefault();t&&(D=!0)}if(this.onmousewheel=function(e){if(m.wheelprevented||m.locked)return!1;if(m.railslocked)return m.debounced("checkunlock",m.resize,250),!1;if(m.rail.drag)return m.cancelEvent(e);if("auto"===g.oneaxismousemode&&0!==e.deltaX&&(g.oneaxismousemode=!1),g.oneaxismousemode&&0===e.deltaX&&!m.rail.scrollable)return!m.railh||!m.railh.scrollable||m.onmousewheelhr(e);var o=w(),t=!1;if(g.preservenativescrolling&&m.checkarea+600<o&&(m.nativescrollingarea=m.isScrollable(e),t=!0),m.checkarea=o,m.nativescrollingarea)return!0;var r=A(e,!1,t);return r&&(m.checkarea=0),r},this.onmousewheelhr=function(e){if(!m.wheelprevented){if(m.railslocked||!m.railh.scrollable)return!0;if(m.rail.drag)return m.cancelEvent(e);var o=w(),t=!1;return g.preservenativescrolling&&m.checkarea+600<o&&(m.nativescrollingarea=m.isScrollable(e),t=!0),m.checkarea=o,!!m.nativescrollingarea||(m.railslocked?m.cancelEvent(e):A(e,!0,t))}},this.stop=function(){return m.cancelScroll(),m.scrollmon&&m.scrollmon.stop(),m.cursorfreezed=!1,m.scroll.y=Math.round(m.getScrollTop()*(1/m.scrollratio.y)),m.noticeCursor(),m},this.getTransitionSpeed=function(e){return 80+e/72*g.scrollspeed|0},g.smoothscroll)if(m.ishwscroll&&T.hastransition&&g.usetransition&&g.smoothscroll){var q="";this.resetTransition=function(){q="",m.doc.css(T.prefixstyle+"transition-duration","0ms")},this.prepareTransition=function(e,o){var t=o?e:m.getTransitionSpeed(e),r=t+"ms";return q!==r&&(q=r,m.doc.css(T.prefixstyle+"transition-duration",r)),t},this.doScrollLeft=function(e,o){var t=m.scrollrunning?m.newscrolly:m.getScrollTop();m.doScrollPos(e,t,o)},this.doScrollTop=function(e,o){var t=m.scrollrunning?m.newscrollx:m.getScrollLeft();m.doScrollPos(t,e,o)},this.cursorupdate={running:!1,start:function(){var e=this;if(!e.running){e.running=!0;var o=function(){e.running&&u(o),m.showCursor(m.getScrollTop(),m.getScrollLeft()),m.notifyScrollEvent(m.win[0])};u(o)}},stop:function(){this.running=!1}},this.doScrollPos=function(e,o,t){var r=m.getScrollTop(),i=m.getScrollLeft();if(((m.newscrolly-r)*(o-r)<0||(m.newscrollx-i)*(e-i)<0)&&m.cancelScroll(),g.bouncescroll?(o<0?o=o/2|0:o>m.page.maxh&&(o=m.page.maxh+(o-m.page.maxh)/2|0),e<0?e=e/2|0:e>m.page.maxw&&(e=m.page.maxw+(e-m.page.maxw)/2|0)):(o<0?o=0:o>m.page.maxh&&(o=m.page.maxh),e<0?e=0:e>m.page.maxw&&(e=m.page.maxw)),m.scrollrunning&&e==m.newscrollx&&o==m.newscrolly)return!1;m.newscrolly=o,m.newscrollx=e;var s=m.getScrollTop(),n=m.getScrollLeft(),l={};l.x=e-n,l.y=o-s;var a=0|Math.sqrt(l.x*l.x+l.y*l.y),c=m.prepareTransition(a);m.scrollrunning||(m.scrollrunning=!0,m.triggerScrollStart(n,s,e,o,c),m.cursorupdate.start()),m.scrollendtrapped=!0,T.transitionend||(m.scrollendtrapped&&clearTimeout(m.scrollendtrapped),m.scrollendtrapped=setTimeout(m.onScrollTransitionEnd,c)),m.setScrollTop(m.newscrolly),m.setScrollLeft(m.newscrollx)},this.cancelScroll=function(){if(!m.scrollendtrapped)return!0;var e=m.getScrollTop(),o=m.getScrollLeft();return m.scrollrunning=!1,T.transitionend||clearTimeout(T.transitionend),m.scrollendtrapped=!1,m.resetTransition(),m.setScrollTop(e),m.railh&&m.setScrollLeft(o),m.timerscroll&&m.timerscroll.tm&&clearInterval(m.timerscroll.tm),m.timerscroll=!1,m.cursorfreezed=!1,m.cursorupdate.stop(),m.showCursor(e,o),m},this.onScrollTransitionEnd=function(){if(m.scrollendtrapped){var e=m.getScrollTop(),o=m.getScrollLeft();if(e<0?e=0:e>m.page.maxh&&(e=m.page.maxh),o<0?o=0:o>m.page.maxw&&(o=m.page.maxw),e!=m.newscrolly||o!=m.newscrollx)return m.doScrollPos(o,e,g.snapbackspeed);m.scrollrunning&&m.triggerScrollEnd(),m.scrollrunning=!1,m.scrollendtrapped=!1,m.resetTransition(),m.timerscroll=!1,m.setScrollTop(e),m.railh&&m.setScrollLeft(o),m.cursorupdate.stop(),m.noticeCursor(!1,e,o),m.cursorfreezed=!1}}}else this.doScrollLeft=function(e,o){var t=m.scrollrunning?m.newscrolly:m.getScrollTop();m.doScrollPos(e,t,o)},this.doScrollTop=function(e,o){var t=m.scrollrunning?m.newscrollx:m.getScrollLeft();m.doScrollPos(t,e,o)},this.doScrollPos=function(e,o,t){var r=m.getScrollTop(),i=m.getScrollLeft();((m.newscrolly-r)*(o-r)<0||(m.newscrollx-i)*(e-i)<0)&&m.cancelScroll();var s=!1;if(m.bouncescroll&&m.rail.visibility||(o<0?(o=0,s=!0):o>m.page.maxh&&(o=m.page.maxh,s=!0)),m.bouncescroll&&m.railh.visibility||(e<0?(e=0,s=!0):e>m.page.maxw&&(e=m.page.maxw,s=!0)),m.scrollrunning&&m.newscrolly===o&&m.newscrollx===e)return!0;m.newscrolly=o,m.newscrollx=e,m.dst={},m.dst.x=e-i,m.dst.y=o-r,m.dst.px=i,m.dst.py=r;var n=0|Math.sqrt(m.dst.x*m.dst.x+m.dst.y*m.dst.y),l=m.getTransitionSpeed(n);m.bzscroll={};var a=s?1:.58;m.bzscroll.x=new E(i,m.newscrollx,l,0,0,a,1),m.bzscroll.y=new E(r,m.newscrolly,l,0,0,a,1);w();var c=function(){if(m.scrollrunning){var e=m.bzscroll.y.getPos();m.setScrollLeft(m.bzscroll.x.getNow()),m.setScrollTop(m.bzscroll.y.getNow()),e<=1?m.timer=u(c):(m.scrollrunning=!1,m.timer=0,m.triggerScrollEnd())}};m.scrollrunning||(m.triggerScrollStart(i,r,e,o,l),m.scrollrunning=!0,m.timer=u(c))},this.cancelScroll=function(){return m.timer&&h(m.timer),m.timer=0,m.bzscroll=!1,m.scrollrunning=!1,m};else this.doScrollLeft=function(e,o){var t=m.getScrollTop();m.doScrollPos(e,t,o)},this.doScrollTop=function(e,o){var t=m.getScrollLeft();m.doScrollPos(t,e,o)},this.doScrollPos=function(e,o,t){var r=e>m.page.maxw?m.page.maxw:e;r<0&&(r=0);var i=o>m.page.maxh?m.page.maxh:o;i<0&&(i=0),m.synched("scroll",function(){m.setScrollTop(i),m.setScrollLeft(r)})},this.cancelScroll=function(){};this.doScrollBy=function(e,o){X(0,e)},this.doScrollLeftBy=function(e,o){X(e,0)},this.doScrollTo=function(e,o){var t=o?Math.round(e*m.scrollratio.y):e;t<0?t=0:t>m.page.maxh&&(t=m.page.maxh),m.cursorfreezed=!1,m.doScrollTop(e)},this.checkContentSize=function(){var e=m.getContentSize();e.h==m.page.h&&e.w==m.page.w||m.resize(!1,e)},m.onscroll=function(e){m.rail.drag||m.cursorfreezed||m.synched("scroll",function(){m.scroll.y=Math.round(m.getScrollTop()/m.scrollratio.y),m.railh&&(m.scroll.x=Math.round(m.getScrollLeft()/m.scrollratio.x)),m.noticeCursor()})},m.bind(m.docscroll,"scroll",m.onscroll),this.doZoomIn=function(e){if(!m.zoomactive){m.zoomactive=!0,m.zoomrestore={style:{}};var o=["position","top","left","zIndex","backgroundColor","marginTop","marginBottom","marginLeft","marginRight"],t=m.win[0].style;for(var r in o){var i=o[r];m.zoomrestore.style[i]=void 0!==t[i]?t[i]:""}m.zoomrestore.style.width=m.win.css("width"),m.zoomrestore.style.height=m.win.css("height"),m.zoomrestore.padding={w:m.win.outerWidth()-m.win.width(),h:m.win.outerHeight()-m.win.height()},T.isios4&&(m.zoomrestore.scrollTop=c.scrollTop(),c.scrollTop(0)),m.win.css({position:T.isios4?"absolute":"fixed",top:0,left:0,zIndex:s+100,margin:0});var n=m.win.css("backgroundColor");return(""===n||/transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(n))&&m.win.css("backgroundColor","#fff"),m.rail.css({zIndex:s+101}),m.zoom.css({zIndex:s+102}),m.zoom.css("backgroundPosition","0 -18px"),m.resizeZoom(),m.onzoomin&&m.onzoomin.call(m),m.cancelEvent(e)}},this.doZoomOut=function(e){if(m.zoomactive)return m.zoomactive=!1,m.win.css("margin",""),m.win.css(m.zoomrestore.style),T.isios4&&c.scrollTop(m.zoomrestore.scrollTop),m.rail.css({"z-index":m.zindex}),m.zoom.css({"z-index":m.zindex}),m.zoomrestore=!1,m.zoom.css("backgroundPosition","0 0"),m.onResize(),m.onzoomout&&m.onzoomout.call(m),m.cancelEvent(e)},this.doZoom=function(e){return m.zoomactive?m.doZoomOut(e):m.doZoomIn(e)},this.resizeZoom=function(){if(m.zoomactive){var e=m.getScrollTop();m.win.css({width:c.width()-m.zoomrestore.padding.w+"px",height:c.height()-m.zoomrestore.padding.h+"px"}),m.onResize(),m.setScrollTop(Math.min(m.page.maxh,e))}},this.init(),n.nicescroll.push(this)},S=function(e){var o=this;this.nc=e,this.lastx=0,this.lasty=0,this.speedx=0,this.speedy=0,this.lasttime=0,this.steptime=0,this.snapx=!1,this.snapy=!1,this.demulx=0,this.demuly=0,this.lastscrollx=-1,this.lastscrolly=-1,this.chkx=0,this.chky=0,this.timer=0,this.reset=function(e,t){o.stop(),o.steptime=0,o.lasttime=w(),o.speedx=0,o.speedy=0,o.lastx=e,o.lasty=t,o.lastscrollx=-1,o.lastscrolly=-1},this.update=function(e,t){var r=w();o.steptime=r-o.lasttime,o.lasttime=r;var i=t-o.lasty,s=e-o.lastx,n=o.nc.getScrollTop()+i,l=o.nc.getScrollLeft()+s;o.snapx=l<0||l>o.nc.page.maxw,o.snapy=n<0||n>o.nc.page.maxh,o.speedx=s,o.speedy=i,o.lastx=e,o.lasty=t},this.stop=function(){o.nc.unsynched("domomentum2d"),o.timer&&clearTimeout(o.timer),o.timer=0,o.lastscrollx=-1,o.lastscrolly=-1},this.doSnapy=function(e,t){var r=!1;t<0?(t=0,r=!0):t>o.nc.page.maxh&&(t=o.nc.page.maxh,r=!0),e<0?(e=0,r=!0):e>o.nc.page.maxw&&(e=o.nc.page.maxw,r=!0),r?o.nc.doScrollPos(e,t,o.nc.opt.snapbackspeed):o.nc.triggerScrollEnd()},this.doMomentum=function(e){var t=w(),r=e?t+e:o.lasttime,i=o.nc.getScrollLeft(),s=o.nc.getScrollTop(),n=o.nc.page.maxh,l=o.nc.page.maxw;o.speedx=l>0?Math.min(60,o.speedx):0,o.speedy=n>0?Math.min(60,o.speedy):0;var a=r&&t-r<=60;(s<0||s>n||i<0||i>l)&&(a=!1);var c=!(!o.speedy||!a)&&o.speedy,d=!(!o.speedx||!a)&&o.speedx;if(c||d){var u=Math.max(16,o.steptime);if(u>50){var h=u/50;o.speedx*=h,o.speedy*=h,u=50}o.demulxy=0,o.lastscrollx=o.nc.getScrollLeft(),o.chkx=o.lastscrollx,o.lastscrolly=o.nc.getScrollTop(),o.chky=o.lastscrolly;var p=o.lastscrollx,m=o.lastscrolly,f=function(){var e=w()-t>600?.04:.02;o.speedx&&(p=Math.floor(o.lastscrollx-o.speedx*(1-o.demulxy)),o.lastscrollx=p,(p<0||p>l)&&(e=.1)),o.speedy&&(m=Math.floor(o.lastscrolly-o.speedy*(1-o.demulxy)),o.lastscrolly=m,(m<0||m>n)&&(e=.1)),o.demulxy=Math.min(1,o.demulxy+e),o.nc.synched("domomentum2d",function(){if(o.speedx){o.nc.getScrollLeft();o.chkx=p,o.nc.setScrollLeft(p)}if(o.speedy){o.nc.getScrollTop();o.chky=m,o.nc.setScrollTop(m)}o.timer||(o.nc.hideCursor(),o.doSnapy(p,m))}),o.demulxy<1?o.timer=setTimeout(f,u):(o.stop(),o.nc.hideCursor(),o.doSnapy(p,m))};f()}else o.doSnapy(o.nc.getScrollLeft(),o.nc.getScrollTop())}},z=e.fn.scrollTop;e.cssHooks.pageYOffset={get:function(e,o,t){var r=n.data(e,"__nicescroll")||!1;return r&&r.ishwscroll?r.getScrollTop():z.call(e)},set:function(e,o){var t=n.data(e,"__nicescroll")||!1;return t&&t.ishwscroll?t.setScrollTop(parseInt(o)):z.call(e,o),this}},e.fn.scrollTop=function(e){if(void 0===e){var o=this[0]&&n.data(this[0],"__nicescroll")||!1;return o&&o.ishwscroll?o.getScrollTop():z.call(this)}return this.each(function(){var o=n.data(this,"__nicescroll")||!1;o&&o.ishwscroll?o.setScrollTop(parseInt(e)):z.call(n(this),e)})};var k=e.fn.scrollLeft;n.cssHooks.pageXOffset={get:function(e,o,t){var r=n.data(e,"__nicescroll")||!1;return r&&r.ishwscroll?r.getScrollLeft():k.call(e)},set:function(e,o){var t=n.data(e,"__nicescroll")||!1;return t&&t.ishwscroll?t.setScrollLeft(parseInt(o)):k.call(e,o),this}},e.fn.scrollLeft=function(e){if(void 0===e){var o=this[0]&&n.data(this[0],"__nicescroll")||!1;return o&&o.ishwscroll?o.getScrollLeft():k.call(this)}return this.each(function(){var o=n.data(this,"__nicescroll")||!1;o&&o.ishwscroll?o.setScrollLeft(parseInt(e)):k.call(n(this),e)})};var T=function(e){var o=this;if(this.length=0,this.name="nicescrollarray",this.each=function(e){return n.each(o,e),o},this.push=function(e){o[o.length]=e,o.length++},this.eq=function(e){return o[e]},e)for(var t=0;t<e.length;t++){var r=n.data(e[t],"__nicescroll")||!1;r&&(this[this.length]=r,this.length++)}return this};!function(e,o,t){for(var r=0,i=o.length;r<i;r++)t(e,o[r])}(T.prototype,["show","hide","toggle","onResize","resize","remove","stop","doScrollPos"],function(e,o){e[o]=function(){var e=arguments;return this.each(function(){this[o].apply(this,e)})}}),e.fn.getNiceScroll=function(e){return void 0===e?new T(this):this[e]&&n.data(this[e],"__nicescroll")||!1},(e.expr.pseudos||e.expr[":"]).nicescroll=function(e){return void 0!==n.data(e,"__nicescroll")},n.fn.niceScroll=function(e,o){void 0!==o||"object"!=typeof e||"jquery"in e||(o=e,e=!1);var t=new T;return this.each(function(){var r=n(this),i=n.extend({},o);if(e){var s=n(e);i.doc=s.length>1?n(e,r):s,i.win=r}!("doc"in i)||"win"in i||(i.win=r);var l=r.data("__nicescroll")||!1;l||(i.doc=i.doc||r,l=new x(i,r),r.data("__nicescroll",l)),t.push(l)}),1===t.length?t[0]:t},a.NiceScroll={getjQuery:function(){return e}},n.nicescroll||(n.nicescroll=new T,n.nicescroll.options=b)}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/legacy.js b/web/main/static/resources/scripts/axure/legacy.js deleted file mode 100644 index a46148a..0000000 --- a/web/main/static/resources/scripts/axure/legacy.js +++ /dev/null @@ -1,166 +0,0 @@ -//stored on each browser event -var windowEvent; - -$axure.internal(function($ax) { - var _legacy = {}; - $ax.legacy = _legacy; - - var Forms = window.document.getElementsByTagName("FORM"); - for(var i = 0; i < Forms.length; i++) { - var Form = Forms[i]; - Form.onclick = $ax.legacy.SuppressBubble; - } - - $ax.legacy.SuppressBubble = function(event) { - if(IE_10_AND_BELOW) { - window.event.cancelBubble = true; - window.event.returnValue = false; - } else { - if(event) { - event.stopPropagation(); - } - } - }; - - $ax.legacy.BringToFront = function(id, skipFixed) { - _bringToFrontHelper(id); - if(!skipFixed) $ax.legacy.BringFixedToFront(); - }; - - var _bringToFrontHelper = function(id) { - var target = window.document.getElementById(id); - if(target == null) return; - $ax.globals.MaxZIndex = $ax.globals.MaxZIndex + 1; - target.style.zIndex = $ax.globals.MaxZIndex; - }; - - $ax.legacy.BringFixedToFront = function() { - $ax(function(diagramObject) { return diagramObject.fixedKeepInFront; }).each(function(diagramObject, scriptId) { - _bringToFrontHelper(scriptId); - }); - }; - - $ax.legacy.SendToBack = function(id) { - var target = window.document.getElementById(id); - if(target == null) return; - target.style.zIndex = $ax.globals.MinZIndex = $ax.globals.MinZIndex - 1; - }; - - $ax.legacy.RefreshScreen = function() { - var oldColor = window.document.body.style.backgroundColor; - var setColor = (oldColor == "rgb(0,0,0)") ? "#FFFFFF" : "#000000"; - window.document.body.style.backgroundColor = setColor; - window.document.body.style.backgroundColor = oldColor; - }; - - $ax.legacy.getAbsoluteLeft = function(currentNode, elementId) { - var oldDisplay = currentNode.css('display'); - var displaySet = false; - if(oldDisplay == 'none') { - currentNode.css('display', ''); - displaySet = true; - } - var left = currentNode.offset().left; - - // Special Layer code - if($ax.getTypeFromElementId(elementId) == 'layer') { - var first = true; - var children = currentNode.children(); - for(var i = 0; i < children.length; i++) { - var child = $(children[i]); - var subDisplaySet = false; - if(child.css('display') == 'none') { - child.css('display', ''); - subDisplaySet = true; - } - if(first) left = child.offset().left; - else left = Math.min(child.offset().left, left); - first = false; - - if(subDisplaySet) child.css('display', 'none'); - } - } - - if (displaySet) currentNode.css('display', oldDisplay); - - return $axure.fn.bodyToWorld(left, true); - }; - - $ax.legacy.getAbsoluteTop = function(currentNode, elementId) { - var oldDisplay = currentNode.css('display'); - var displaySet = false; - if(oldDisplay == 'none') { - currentNode.css('display', ''); - displaySet = true; - } - var top = currentNode.offset().top; - - // Special Layer code - if ($ax.getTypeFromElementId(elementId) == 'layer') { - var first = true; - var children = currentNode.children(); - for (var i = 0; i < children.length; i++) { - var child = $(children[i]); - var subDisplaySet = false; - if (child.css('display') == 'none') { - child.css('display', ''); - subDisplaySet = true; - } - if (first) top = child.offset().top; - else top = Math.min(child.offset().top, top); - first = false; - - if (subDisplaySet) child.css('display', 'none'); - } - } - - if(displaySet) currentNode.css('display', oldDisplay); - return top; - }; - - // ****************** Annotation and Link Functions ****************** // - - $ax.legacy.GetAnnotationHtml = function(annJson) { - var retVal = ""; - for(var noteName in annJson) { - if(noteName != "label" && noteName != "id") { - retVal += "<div class='annotationName'>" + noteName + "</div>"; - retVal += "<div class='annotationValue'>" + linkify(annJson[noteName]) + "</div>"; - } - } - return retVal; - - function linkify(text) { - var urlRegex = /(\b(((https?|ftp|file):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; - return text.replace(urlRegex, function (url, b, c) { - var url2 = (c == 'www.') ? 'http://' + url : url; - return '<a href="' + url2 + '" target="_blank" class="noteLink">' + url + '</a>'; - }); - } - }; - - - $ax.legacy.GetScrollable = function(target) { - var $target = $(target); - var last = $target; - // Start past inital target. Can't scroll to target in itself, must be some ancestor. - var current = last.parent(); - - while(!current.is('body') && !current.is('html')) { - var elementId = current.attr('id'); - var diagramObject = elementId && $ax.getObjectFromElementId(elementId); - if (diagramObject && $ax.public.fn.IsDynamicPanel(diagramObject.type) && diagramObject.scrollbars != 'none') { - //returns the panel diagram div which handles scrolling - return $ax.dynamicPanelManager.getShownState(current.attr('id'))[0]; - } - last = current; - current = current.parent(); - } - // Need to do this because of ie - if(IE_10_AND_BELOW) return window.document.documentElement; - else return window.document.body; - }; - - - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/math.js b/web/main/static/resources/scripts/axure/math.js deleted file mode 100644 index cf2f75d..0000000 --- a/web/main/static/resources/scripts/axure/math.js +++ /dev/null @@ -1,554 +0,0 @@ -$axure.internal(function($ax) { - $ax.public.fn.matrixMultiply = function(matrix, vector) { - if(!matrix.tx) matrix.tx = 0; - if(!matrix.ty) matrix.ty = 0; - var outX = matrix.m11 * vector.x + matrix.m12 * vector.y + matrix.tx; - var outY = matrix.m21 * vector.x + matrix.m22 * vector.y + matrix.ty; - return { x: outX, y: outY }; - } - - $ax.public.fn.matrixInverse = function(matrix) { - if(!matrix.tx) matrix.tx = 0; - if(!matrix.ty) matrix.ty = 0; - - var determinant = matrix.m11*matrix.m22 - matrix.m12*matrix.m21; - //var threshold = (M11 * M11 + M22 *M22 + M12 *M12+ M21 *M21) / 100000; - //if(determinant.DeltaEquals(0, threshold) && determinant < 0.01) { - // return Invalid; - //} - return { - m11 : matrix.m22/determinant, - m12 : -matrix.m12/determinant, - tx : (matrix.ty*matrix.m12 - matrix.tx*matrix.m22)/determinant, - m21: -matrix.m21 / determinant, - m22: matrix.m11 / determinant, - ty: (matrix.tx * matrix.m21 - matrix.ty * matrix.m11) / determinant - }; - } - - - $ax.public.fn.matrixMultiplyMatrix = function (matrix1, matrix2) { - if (!matrix1.tx) matrix1.tx = 0; - if (!matrix1.ty) matrix1.ty = 0; - if (!matrix2.tx) matrix2.tx = 0; - if (!matrix2.ty) matrix2.ty = 0; - - return { - m11: matrix1.m12*matrix2.m21 + matrix1.m11*matrix2.m11, - m12: matrix1.m12*matrix2.m22 + matrix1.m11*matrix2.m12, - tx: matrix1.m12 * matrix2.ty + matrix1.m11 * matrix2.tx + matrix1.tx, - m21: matrix1.m22 * matrix2.m21 + matrix1.m21 * matrix2.m11, - m22: matrix1.m22 * matrix2.m22 + matrix1.m21 * matrix2.m12, - ty: matrix1.m22 * matrix2.ty + matrix1.m21 * matrix2.tx + matrix1.ty, - }; - } - - - $ax.public.fn.transformFromElement = function (element) { - var st = window.getComputedStyle(element, null); - - var tr = st.getPropertyValue("-webkit-transform") || - st.getPropertyValue("-moz-transform") || - st.getPropertyValue("-ms-transform") || - st.getPropertyValue("-o-transform") || - st.getPropertyValue("transform"); - - if (tr.indexOf('none') < 0) { - var matrix = tr.split('(')[1]; - matrix = matrix.split(')')[0]; - matrix = matrix.split(','); - for (var l = 0; l < matrix.length; l++) { - matrix[l] = Number(matrix[l]); - } - - } else { matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; } - - return matrix; - // matrix[0] = cosine, matrix[1] = sine. - // Assuming the element is still orthogonal. - } - - $ax.public.fn.vectorMinus = function(vector1, vector2) { return { x: vector1.x - vector2.x, y: vector1.y - vector2.y }; } - - $ax.public.fn.vectorPlus = function (vector1, vector2) { return { x: vector1.x + vector2.x, y: vector1.y + vector2.y }; } - - $ax.public.fn.vectorMidpoint = function (vector1, vector2) { return { x: (vector1.x + vector2.x) / 2.0, y: (vector1.y + vector2.y) / 2.0 }; } - - $ax.public.fn.fourCornersToBasis = function (fourCorners) { - return { - widthVector: $ax.public.fn.vectorMinus(fourCorners.widgetTopRight, fourCorners.widgetTopLeft), - heightVector: $ax.public.fn.vectorMinus(fourCorners.widgetBottomLeft, fourCorners.widgetTopLeft) - }; - } - - $ax.public.fn.matrixString = function(m11, m21, m12, m22, tx, ty) { - return "Matrix(" + m11 + "," + m21 + "," + m12 + "," + m22 + ", " + tx + ", " + ty + ")"; - } - - //$ax.public.fn.getWidgetBoundingRect = function (widgetId) { - // var emptyRect = { left: 0, top: 0, centerPoint: { x: 0, y: 0 }, width: 0, height: 0 }; - // var element = document.getElementById(widgetId); - // if (!element) return emptyRect; - - // var object = $obj(widgetId); - // if (object && object.type && $ax.public.fn.IsLayer(object.type)) { - // var layerChildren = _getLayerChildrenDeep(widgetId); - // if (!layerChildren) return emptyRect; - // else return _getBoundingRectForMultipleWidgets(layerChildren); - // } - // return _getBoundingRectForSingleWidget(widgetId); - //}; - - var _getLayerChildrenDeep = $ax.public.fn.getLayerChildrenDeep = function (layerId, includeLayers, includeHidden) { - var deep = []; - var children = $ax('#' + layerId).getChildren()[0].children; - for (var index = 0; index < children.length; index++) { - var childId = children[index]; - if(!includeHidden && !$ax.visibility.IsIdVisible(childId)) continue; - if ($ax.public.fn.IsLayer($obj(childId).type)) { - if (includeLayers) deep.push(childId); - var recursiveChildren = _getLayerChildrenDeep(childId, includeLayers, includeHidden); - for (var j = 0; j < recursiveChildren.length; j++) deep.push(recursiveChildren[j]); - } else deep.push(childId); - } - return deep; - }; - - //var _getBoundingRectForMultipleWidgets = function (widgetsIdArray, relativeToPage) { - // if (!widgetsIdArray || widgetsIdArray.constructor !== Array) return undefined; - // if (widgetsIdArray.length == 0) return { left: 0, top: 0, centerPoint: { x: 0, y: 0 }, width: 0, height: 0 }; - // var widgetRect = _getBoundingRectForSingleWidget(widgetsIdArray[0], relativeToPage, true); - // var boundingRect = { left: widgetRect.left, right: widgetRect.right, top: widgetRect.top, bottom: widgetRect.bottom }; - - // for (var index = 1; index < widgetsIdArray.length; index++) { - // widgetRect = _getBoundingRectForSingleWidget(widgetsIdArray[index], relativeToPage); - // boundingRect.left = Math.min(boundingRect.left, widgetRect.left); - // boundingRect.top = Math.min(boundingRect.top, widgetRect.top); - // boundingRect.right = Math.max(boundingRect.right, widgetRect.right); - // boundingRect.bottom = Math.max(boundingRect.bottom, widgetRect.bottom); - // } - - // boundingRect.centerPoint = { x: (boundingRect.right + boundingRect.left) / 2.0, y: (boundingRect.bottom + boundingRect.top) / 2.0 }; - // boundingRect.width = boundingRect.right - boundingRect.left; - // boundingRect.height = boundingRect.bottom - boundingRect.top; - // return boundingRect; - //}; - - //var _getBoundingRectForSingleWidget = function (widgetId, relativeToPage, justSides) { - // var element = document.getElementById(widgetId); - // var boundingRect, tempBoundingRect, position; - // var displayChanged = _displayHackStart(element); - - // if (_isCompoundVectorHtml(element)) { - // //tempBoundingRect = _getCompoundImageBoundingClientSize(widgetId); - // //position = { left: tempBoundingRect.left, top: tempBoundingRect.top }; - // position = $(element).position(); - // tempBoundingRect = {}; - // tempBoundingRect.left = position.left; //= _getCompoundImageBoundingClientSize(widgetId); - // tempBoundingRect.top = position.top; - // tempBoundingRect.width = Number(element.getAttribute('data-width')); - // tempBoundingRect.height = Number(element.getAttribute('data-height')); - // } else { - // var boundingElement = element; - // if($ax.dynamicPanelManager.isIdFitToContent(widgetId)) { - // var stateId = $ax.visibility.GetPanelState(widgetId); - // if(stateId != '') boundingElement = document.getElementById(stateId); - // } - // tempBoundingRect = boundingElement.getBoundingClientRect(); - - // var jElement = $(element); - // position = jElement.position(); - // if(jElement.css('position') == 'fixed') { - // position.left += Number(jElement.css('margin-left').replace("px", "")); - // position.top += Number(jElement.css('margin-top').replace("px", "")); - // } - // } - - // var layers = $ax('#' + widgetId).getParents(true, ['layer'])[0]; - // var flip = ''; - // var mirrorWidth = 0; - // var mirrorHeight = 0; - // for (var i = 0; i < layers.length; i++) { - - // //should always be 0,0 - // var layerPos = $jobj(layers[i]).position(); - // position.left += layerPos.left; - // position.top += layerPos.top; - - // var outer = $ax.visibility.applyWidgetContainer(layers[i], true, true); - // if (outer.length) { - // var outerPos = outer.position(); - // position.left += outerPos.left; - // position.top += outerPos.top; - // } - - // //when a group is flipped we find the unflipped position - // var inner = $jobj(layers[i] + '_container_inner'); - // var taggedFlip = inner.data('flip'); - // if (inner.length && taggedFlip) { - // //only account for flip if transform is applied - // var matrix = taggedFlip && (inner.css("-webkit-transform") || inner.css("-moz-transform") || - // inner.css("-ms-transform") || inner.css("-o-transform") || inner.css("transform")); - // if (matrix !== 'none') { - // flip = taggedFlip; - // mirrorWidth = $ax.getNumFromPx(inner.css('width')); - // mirrorHeight = $ax.getNumFromPx(inner.css('height')); - // } - // } - // } - // //Now account for flip - // if (flip == 'x') position.top = mirrorHeight - position.top - element.getBoundingClientRect().height; - // else if (flip == 'y') position.left = mirrorWidth - position.left - element.getBoundingClientRect().width; - - // boundingRect = { - // left: position.left, - // right: position.left + tempBoundingRect.width, - // top: position.top, - // bottom: position.top + tempBoundingRect.height - // }; - - // _displayHackEnd(displayChanged); - // if (justSides) return boundingRect; - - // boundingRect.width = boundingRect.right - boundingRect.left; - // boundingRect.height = boundingRect.bottom - boundingRect.top; - - // boundingRect.centerPoint = { - // x: boundingRect.width / 2 + boundingRect.left, - // y: boundingRect.height / 2 + boundingRect.top - // }; - - // return boundingRect; - //}; - - var _getPointAfterRotate = $ax.public.fn.getPointAfterRotate = function (angleInDegrees, pointToRotate, centerPoint) { - var displacement = $ax.public.fn.vectorMinus(pointToRotate, centerPoint); - var rotationMatrix = $ax.public.fn.rotationMatrix(angleInDegrees); - rotationMatrix.tx = centerPoint.x; - rotationMatrix.ty = centerPoint.y; - return $ax.public.fn.matrixMultiply(rotationMatrix, displacement); - }; - - $ax.public.fn.getBoundingSizeForRotate = function(width, height, rotation) { - // point to rotate around doesn't matter since we just care about size, if location matter we need more args and location matters. - - var origin = { x: 0, y: 0 }; - - var corner1 = { x: width, y: 0 }; - var corner2 = { x: 0, y: height }; - var corner3 = { x: width, y: height }; - - corner1 = _getPointAfterRotate(rotation, corner1, origin); - corner2 = _getPointAfterRotate(rotation, corner2, origin); - corner3 = _getPointAfterRotate(rotation, corner3, origin); - - var left = Math.min(0, corner1.x, corner2.x, corner3.x); - var right = Math.max(0, corner1.x, corner2.x, corner3.x); - var top = Math.min(0, corner1.y, corner2.y, corner3.y); - var bottom = Math.max(0, corner1.y, corner2.y, corner3.y); - - return { width: right - left, height: bottom - top }; - } - - $ax.public.fn.getBoundingRectForRotate = function (boundingRect, rotation) { - var centerPoint = boundingRect.centerPoint; - var corner1 = { x: boundingRect.left, y: boundingRect.top }; - var corner2 = { x: boundingRect.right, y: boundingRect.top }; - var corner3 = { x: boundingRect.right, y: boundingRect.bottom }; - var corner4 = { x: boundingRect.left, y: boundingRect.bottom }; - corner1 = _getPointAfterRotate(rotation, corner1, centerPoint); - corner2 = _getPointAfterRotate(rotation, corner2, centerPoint); - corner3 = _getPointAfterRotate(rotation, corner3, centerPoint); - corner4 = _getPointAfterRotate(rotation, corner4, centerPoint); - - var left = Math.min(corner1.x, corner2.x, corner3.x, corner4.x); - var right = Math.max(corner1.x, corner2.x, corner3.x, corner4.x); - var top = Math.min(corner1.y, corner2.y, corner3.y, corner4.y); - var bottom = Math.max(corner1.y, corner2.y, corner3.y, corner4.y); - - return { left: left, top: top, width: right - left, height: bottom - top }; - } - - - //$ax.public.fn.getPositionRelativeToParent = function (elementId) { - // var element = document.getElementById(elementId); - // var list = _displayHackStart(element); - // var position = $(element).position(); - // _displayHackEnd(list); - // return position; - //}; - - //var _displayHackStart = $ax.public.fn.displayHackStart = function (element) { - // // TODO: Options: 1) stop setting display none. Big change for this late in the game. 2) Implement our own bounding. - // // TODO: 3) Current method is look for any parents that are set to none, and and temporarily unblock. Don't like it, but it works. - // var parent = element; - // var displays = []; - // while (parent) { - // if (parent.style.display == 'none') { - // displays.push(parent); - // //use block to overwrites default hidden objects' display - // parent.style.display = 'block'; - // } - // parent = parent.parentElement; - // } - - // return displays; - //}; - - //var _displayHackEnd = $ax.public.fn.displayHackEnd = function (displayChangedList) { - // for (var i = 0; i < displayChangedList.length; i++) displayChangedList[i].style.display = 'none'; - //}; - - - var _isCompoundVectorHtml = $ax.public.fn.isCompoundVectorHtml = function(hElement) { - return hElement.hasAttribute('compoundmode') && hElement.getAttribute('compoundmode') == "true"; - } - - $ax.public.fn.removeCompound = function (jobj) { if(_isCompoundVectorHtml(jobj[0])) jobj.removeClass('compound'); } - $ax.public.fn.restoreCompound = function (jobj) { if (_isCompoundVectorHtml(jobj[0])) jobj.addClass('compound'); } - - $ax.public.fn.compoundIdFromComponent = function(id) { - - var pPos = id.indexOf('p'); - var dashPos = id.indexOf('-'); - if (pPos < 1) return id; - else if (dashPos < 0) return id.substring(0, pPos); - else return id.substring(0, pPos) + id.substring(dashPos); - } - - $ax.public.fn.l2 = function (x, y) { return Math.sqrt(x * x + y * y); } - - $ax.public.fn.convertToSingleImage = function (jobj) { - if(!jobj[0]) return; - - var widgetId = jobj[0].id; - var object = $obj(widgetId); - - if ($ax.public.fn.IsLayer(object.type)) { - var recursiveChildren = _getLayerChildrenDeep(widgetId, true); - for (var j = 0; j < recursiveChildren.length; j++) - $ax.public.fn.convertToSingleImage($jobj(recursiveChildren[j])); - return; - } - - //var layer = - - if(!_isCompoundVectorHtml(jobj[0])) return; - - - $('#' + widgetId).removeClass("compound"); - $('#' + widgetId + '_img').removeClass("singleImg"); - jobj[0].setAttribute('compoundmode', 'false'); - - var components = object.compoundChildren; - delete object.generateCompound; - for (var i = 0; i < components.length; i++) { - var componentJobj = $jobj($ax.public.fn.getComponentId(widgetId, components[i])); - componentJobj.css('display', 'none'); - componentJobj.css('visibility', 'hidden'); - } - } - - - $ax.public.fn.getContainerDimensions = function(query) { - // returns undefined if no containers found. - var containerDimensions; - for (var i = 0; i < query[0].children.length; i++) { - var node = query[0].children[i]; - if (node.id.indexOf(query[0].id) >= 0 && node.id.indexOf('container') >= 0) { - containerDimensions = node.style; - } - } - return containerDimensions; - } - - - $ax.public.fn.rotationMatrix = function (angleInDegrees) { - var angleInRadians = angleInDegrees * (Math.PI / 180); - var cosTheta = Math.cos(angleInRadians); - var sinTheta = Math.sin(angleInRadians); - - return { m11: cosTheta, m12: -sinTheta, m21: sinTheta, m22: cosTheta, tx: 0.0, ty: 0.0 }; - } - - $ax.public.fn.GetFieldFromStyle = function (query, field) { - var raw = query[0].style[field]; - if (!raw) raw = query.css(field); - return Number(raw.replace('px', '')); - } - - - $ax.public.fn.setTransformHowever = function (transformString) { - return { - '-webkit-transform': transformString, - '-moz-transform': transformString, - '-ms-transform': transformString, - '-o-transform': transformString, - 'transform': transformString - }; - } - - $ax.public.fn.getCornersFromComponent = function (id) { - var element = document.getElementById(id); - var matrix = element ? $ax.public.fn.transformFromElement(element) : [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; - var currentMatrix = { m11: matrix[0], m21: matrix[1], m12: matrix[2], m22: matrix[3], tx: matrix[4], ty: matrix[5] }; - var dimensions = {}; - var axObj = $ax('#' + id); - var viewportLocation = axObj.offsetLocation(); - dimensions.left = viewportLocation.left; - dimensions.top = viewportLocation.top; - //dimensions.left = axObj.left(true); - //dimensions.top = axObj.top(true); - var size = axObj.size(); - dimensions.width = size.width; - dimensions.height = size.height; - //var transformMatrix1 = { m11: 1, m12: 0, m21: 0, m22: 1, tx: -invariant.x, ty: -invariant.y }; - //var transformMatrix2 = { m11: 1, m12: 0, m21: 0, m22: 1, tx: 500, ty: 500 }; - - var halfWidth = dimensions.width * 0.5; - var halfHeight = dimensions.height * 0.5; - //var preTransformTopLeft = { x: -halfWidth, y: -halfHeight }; - //var preTransformBottomLeft = { x: -halfWidth, y: halfHeight }; - var preTransformTopRight = { x: halfWidth, y: -halfHeight }; - var preTransformBottomRight = { x: halfWidth, y: halfHeight }; - - return { - //relativeTopLeft: $ax.public.fn.matrixMultiply(currentMatrix, preTransformTopLeft), - //relativeBottomLeft: $ax.public.fn.matrixMultiply(currentMatrix, preTransformBottomLeft), - relativeTopRight: $ax.public.fn.matrixMultiply(currentMatrix, preTransformTopRight), - relativeBottomRight: $ax.public.fn.matrixMultiply(currentMatrix, preTransformBottomRight), - centerPoint: { x: dimensions.left + halfWidth, y: dimensions.top + halfHeight } - //originalDimensions: dimensions, - //transformShift: { x: matrix[4], y: matrix[5] } - } - } - - - - $ax.public.fn.inversePathLengthFunction = function (pathFunction) { - // these are for computing the inverse functions of path integrals. - - var makeDivisionNode = function(node1, node2) { - var param = 0.5 * (node1.Param + node2.Param); - var inBetweenNode = { - LowerStop: node1, - HigherStop: node2, - Param: param, - Position: pathFunction(param), - Cumulative: 0.0 - }; - var lowerDisplacement = $ax.public.fn.vectorMinus(node1.Position, inBetweenNode.Position); - inBetweenNode.LowerInterval = { - Length: $ax.public.fn.l2(lowerDisplacement.x, lowerDisplacement.y), - Node: inBetweenNode, - IsHigher: false - }; - var higherDisplacement = $ax.public.fn.vectorMinus(node2.Position, inBetweenNode.Position); - inBetweenNode.HigherInterval = { - Length: $ax.public.fn.l2(higherDisplacement.x, higherDisplacement.y), - Node: inBetweenNode, - IsHigher: true - }; - return inBetweenNode; - }; - - var expandLower = function(node) { - node.LowerChild = makeDivisionNode(node.LowerStop, node); - node.LowerChild.Parent = node; - }; - - var expandHigher = function(node) { - node.HigherChild = makeDivisionNode(node, node.HigherStop); - node.HigherChild.Parent = node; - }; - - // for this function, cumulative is a global variable - var cumulative = 0.0; - var labelCumulativeLength = function(node) { - if(!node.LowerChild) { - node.LowerStop.Cumulative = cumulative; - cumulative += node.LowerInterval.Length; - node.Cumulative = cumulative; - } else labelCumulativeLength(node.LowerChild); - - if(!node.HigherChild) { - node.Cumulative = cumulative; - cumulative += node.HigherInterval.Length; - node.HigherStop.Cumulative = cumulative; - } else labelCumulativeLength(node.HigherChild); - }; - - var getIntervalFromPathLength = function(node, length) { - if(length < node.Cumulative) { - return node.LowerChild ? getIntervalFromPathLength(node.LowerChild, length) : node.LowerInterval; - } else return node.HigherChild ? getIntervalFromPathLength(node.HigherChild, length) : node.HigherInterval; - }; - - var intervalLowerEnd = function(interval) { - return interval.IsHigher ? interval.Node : interval.Node.LowerStop; - }; - - var intervalHigherEnd = function(interval) { - return interval.IsHigher ? interval.Node.HigherStop : interval.Node; - }; - - var getParameterFromPathLength = function (node, length) { - var interval = getIntervalFromPathLength(node, length); - var lowerNode = intervalLowerEnd(interval); - var higherNode = intervalHigherEnd(interval); - return lowerNode.Param + (higherNode.Param - lowerNode.Param) * (length - lowerNode.Cumulative) / (higherNode.Cumulative - lowerNode.Cumulative); - }; - - var insertIntoSortedList = function (longer, shorter, toInsert) { - while (true) { - if (!longer) { - longer = shorter; - shorter = shorter.NextLongest; - continue; - } else if (!shorter) longer.NextLongest = toInsert; - else { - if (longer.Length >= toInsert.Length && shorter.Length <= toInsert.Length) { - longer.NextLongest = toInsert; - toInsert.NextLongest = shorter; - } else { - longer = shorter; - shorter = shorter.NextLongest; - continue; - } - } - break; - } - } - var head = {Param: 0.0, Position: pathFunction(0.0) }; - var tail = { Param: 1.0, Position: pathFunction(1.0) }; - var root = makeDivisionNode(head, tail); - var currentCurveLength = root.LowerInterval.Length + root.HigherInterval.Length; - var longestInterval; - if (root.LowerInterval.Length < root.HigherInterval.Length) { - longestInterval = root.HigherInterval; - longestInterval.NextLongest = root.LowerInterval; - } else { - longestInterval = root.LowerInterval; - longestInterval.NextLongest = root.HigherInterval; - } - while (longestInterval.Length * 100.0 > currentCurveLength) { - var newNode; - if (longestInterval.IsHigher) { - expandHigher(longestInterval.Node); - newNode = longestInterval.Node.HigherChild; - } else { - expandLower(longestInterval.Node); - newNode = longestInterval.Node.LowerChild; - } - currentCurveLength += (newNode.LowerInterval.Length + newNode.HigherInterval.Length - longestInterval.Length); - insertIntoSortedList(null, longestInterval, newNode.LowerInterval); - insertIntoSortedList(null, longestInterval, newNode.HigherInterval); - longestInterval = longestInterval.NextLongest; - } - labelCumulativeLength(root); - - return function(lengthParam) { - return getParameterFromPathLength(root, lengthParam * cumulative); - }; - } -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/model.js b/web/main/static/resources/scripts/axure/model.js deleted file mode 100644 index ffc0a10..0000000 --- a/web/main/static/resources/scripts/axure/model.js +++ /dev/null @@ -1,53 +0,0 @@ -// ******* Object Model ******** // -$axure.internal(function($ax) { - var _implementations = {}; - - var _initializeObject = function(type, obj) { - $.extend(obj, _implementations[type]); - }; - $ax.initializeObject = _initializeObject; - - var _model = $ax.model = {}; - - _model.idsInRdoToHideOrLimbo = function(rdoId, scriptIds) { - var rdoScriptId = $ax.repeater.getScriptIdFromElementId(rdoId); - var path = $ax.getPathFromScriptId(rdoScriptId); - - if(!scriptIds) scriptIds = []; - - var rdo = $ax.getObjectFromElementId(rdoId); - var master = $ax.pageData.masters[rdo.masterId]; - var masterChildren = master.diagram.objects; - for(var i = 0; i < masterChildren.length; i++) { - var obj = masterChildren[i]; - var objScriptIds = obj.scriptIds; - for(var j = 0; j < objScriptIds.length; j++) { - var scriptId = objScriptIds[j]; - // Anything in a layer is already handled by the layer - if($ax.getLayerParentFromElementId(scriptId)) continue; - - // Make sure in same rdo - var elementPath = $ax.getPathFromScriptId(scriptId); - - // This is because last part of path is for the obj itself. - elementPath.pop(); - if(elementPath.length != path.length) continue; - var samePath = true; - for(var k = 0; k < path.length; k++) { - if(elementPath[k] != path[k]) { - samePath = false; - break; - } - } - if(!samePath) continue; - - if($ax.public.fn.IsReferenceDiagramObject(obj.type)) _model.idsInRdoToHideOrLimbo(scriptId, scriptIds); - else if(scriptIds.indexOf(scriptId) == -1) scriptIds.push(scriptId); - - break; - } - } - return scriptIds; - }; - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/move.js b/web/main/static/resources/scripts/axure/move.js deleted file mode 100644 index 9c9224d..0000000 --- a/web/main/static/resources/scripts/axure/move.js +++ /dev/null @@ -1,467 +0,0 @@ -$axure.internal(function($ax) { - var _move = {}; - $ax.move = _move; - - var widgetMoveInfo = {}; - //register and return move info, also create container for rootlayer if needed - $ax.move.PrepareForMove = function (id, x, y, to, options, jobj, rootLayer, skipContainerForRootLayer) { - var fixedInfo = jobj ? {} : $ax.dynamicPanelManager.getFixedInfo(id); - - var widget = $jobj(id); - var query = $ax('#' + id); - var isLayer = $ax.getTypeFromElementId(id) == $ax.constants.LAYER_TYPE; - if(!rootLayer) { - rootLayer = _move.getRootLayer(id); - if (rootLayer && !skipContainerForRootLayer) { - $ax.visibility.pushContainer(rootLayer, false); - if (isLayer) widget = $ax.visibility.applyWidgetContainer(id, true); - } - } - if (!jobj) jobj = widget; - - var horzProp = 'left'; - var vertProp = 'top'; - var offsetLocation = to ? query.offsetLocation() : undefined; - var horzX = to ? x - offsetLocation.x : x; - var vertY = to ? y - offsetLocation.y : y; - //var horzX = to ? x - query.locRelativeIgnoreLayer(false) : x; - //var vertY = to ? y - query.locRelativeIgnoreLayer(true) : y; - - if (fixedInfo.horizontal == 'right') { - horzProp = 'right'; - horzX = to ? $(window).width() - x - $ax.getNumFromPx(jobj.css('right')) - query.width() : -x; - var leftChanges = -horzX; - } else if(fixedInfo.horizontal == 'center') { - horzProp = 'margin-left'; - if (to) horzX = x - $(window).width() / 2; - } - - if (fixedInfo.vertical == 'bottom') { - vertProp = 'bottom'; - vertY = to ? $(window).height() - y - $ax.getNumFromPx(jobj.css('bottom')) - query.height() : -y; - var topChanges = -vertY; - } else if (fixedInfo.vertical == 'middle') { - vertProp = 'margin-top'; - if (to) vertY = y - $(window).height() / 2; - } - - //todo currently this always save the info, which is not needed for compound vector children and maybe some other cases - //let's optimize it later, only register if registerid is valid.. - widgetMoveInfo[id] = { - x: leftChanges === undefined ? horzX : leftChanges, - y: topChanges === undefined ? vertY : topChanges, - options: options - }; - - return { - horzX: horzX, - vertY: vertY, - horzProp: horzProp, - vertProp: vertProp, - rootLayer: rootLayer, - jobj: jobj - }; - }; - $ax.move.GetWidgetMoveInfo = function() { - return $.extend({}, widgetMoveInfo); - }; - - _move.getRootLayer = function (id) { - var isLayer = $ax.getTypeFromElementId(id) == $ax.constants.LAYER_TYPE; - var rootLayer = isLayer ? id : ''; - - var parentIds = $ax('#' + id).getParents(true, '*')[0]; - for(var i = 0; i < parentIds.length; i++) { - var parentId = parentIds[i]; - // Keep climbing up layers until you hit a non-layer. At that point you have your root layer - if($ax.public.fn.IsLayer($ax.getTypeFromElementId(parentId))) rootLayer = parentId; - else break; - } - - return rootLayer; - }; - - $ax.move.MoveWidget = function (id, x, y, options, to, animationCompleteCallback, shouldFire, jobj, skipOnMoveEvent) { - var moveInfo = $ax.move.PrepareForMove(id, x, y, to, options, jobj); - $ax.drag.LogMovedWidgetForDrag(id, options.dragInfo); - - var object = $obj(id); - if(object && $ax.public.fn.IsLayer(object.type)) { - var childrenIds = $ax.public.fn.getLayerChildrenDeep(id, true); - //don't push container when register moveinfo for child - if(!skipOnMoveEvent) { - for(var i = 0; i < childrenIds.length; i++) $ax.move.PrepareForMove(childrenIds[i], x, y, to, options, null, moveInfo.rootLayer, true); - } - } - - //if(!moveInfo) moveInfo = _getMoveInfo(id, x, y, to, options, jobj); - - jobj = moveInfo.jobj; - - _moveElement(id, options, animationCompleteCallback, shouldFire, jobj, moveInfo); - - if(skipOnMoveEvent) return; - $ax.event.raiseSyntheticEvent(id, "onMove"); - if(childrenIds) { - for(var i = 0; i < childrenIds.length; i++) $ax.event.raiseSyntheticEvent(childrenIds[i], 'onMove'); - } - }; - - var _moveElement = function (id, options, animationCompleteCallback, shouldFire, jobj, moveInfo){ - var cssStyles = {}; - - if(!$ax.dynamicPanelManager.isPercentWidthPanel($obj(id))) cssStyles[moveInfo.horzProp] = '+=' + moveInfo.horzX; - cssStyles[moveInfo.vertProp] = '+=' + moveInfo.vertY; - - $ax.visibility.moveMovedLocation(id, moveInfo.horzX, moveInfo.vertY); - - // I don't think root layer is necessary anymore after changes to layer container structure. - // Wait to try removing it until more stable. - var rootLayer = moveInfo.rootLayer; - - var query = $addAll(jobj, id); - var completeCount = query.length; - var completeAnimation = function() { - completeCount--; - if(completeCount == 0 && rootLayer) $ax.visibility.popContainer(rootLayer, false); - if(animationCompleteCallback) animationCompleteCallback(); - if(shouldFire) $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.move); - }; - if (options.easing === 'none') { - //if not having this requestAnimationFrame causes performance issues, - //add it back and move the above call to moveMovedLocation into it and the - //query.animate calls below - //window.requestAnimationFrame(function () { - query.css(cssStyles); - if (rootLayer) $ax.visibility.popContainer(rootLayer, false); - if (animationCompleteCallback) animationCompleteCallback(); - //}); - //if this widget is inside a layer, we should just remove the layer from the queue - if(shouldFire) $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.move); - } else if (options.trajectory === 'straight' || moveInfo.horzX === 0 || moveInfo.vertY === 0) { - query.animate(cssStyles, { - duration: options.duration, easing: options.easing, queue: false, complete: completeAnimation}); - } else { - var initialHorzProp = $ax.getNumFromPx(query.css(moveInfo.horzProp)); - var initialVertProp = $ax.getNumFromPx(query.css(moveInfo.vertProp)); - var state = { parameter: 0 }; - var ellipseArcFunctionY = function(param) { - return { - x: initialHorzProp + (1.0 - Math.cos(param * Math.PI * 0.5)) * moveInfo.horzX, - y: initialVertProp + Math.sin(param * Math.PI * 0.5) * moveInfo.vertY - }; - }; - var ellipseArcFunctionX = function (param) { - return { - x: initialHorzProp + Math.sin(param * Math.PI * 0.5) * moveInfo.horzX, - y: initialVertProp + (1.0 - Math.cos(param * Math.PI * 0.5)) * moveInfo.vertY - }; - }; - var ellipseArcFunction = (moveInfo.horzX > 0) ^ (moveInfo.vertY > 0) ^ options.trajectory === 'arcClockwise' - ? ellipseArcFunctionX : ellipseArcFunctionY; - var inverseFunction = $ax.public.fn.inversePathLengthFunction(ellipseArcFunction); - $(state).animate({ parameter: 1.0 }, { - duration: options.duration, easing: options.easing, queue: false, - step: function (now) { - var newPos = ellipseArcFunction(inverseFunction(now)); - var changeFields = {}; - changeFields[moveInfo.horzProp] = newPos.x; - changeFields[moveInfo.vertProp] = newPos.y; - query.css(changeFields); - }, - complete: completeAnimation}); - } - - // //moveinfo is used for moving 'with this' - // var moveInfo = new Object(); - // moveInfo.x = horzX; - // moveInfo.y = vertY; - // moveInfo.options = options; - // widgetMoveInfo[id] = moveInfo; - - - }; - - _move.nopMove = function(id, options) { - var moveInfo = new Object(); - moveInfo.x = 0; - moveInfo.y = 0; - moveInfo.options = {}; - moveInfo.options.easing = 'none'; - moveInfo.options.duration = 0; - widgetMoveInfo[id] = moveInfo; - - // Layer move using container now. - var obj = $obj(id); - if($ax.public.fn.IsLayer(obj.type)) if(options.onComplete) options.onComplete(); - - $ax.event.raiseSyntheticEvent(id, "onMove"); - }; - - //rotationDegree: total degree to rotate - //centerPoint: the center of the circular path - - - var _noRotateOnlyMove = function (id, moveDelta, rotatableMove, fireAnimationQueue, easing, duration, completionCallback) { - moveDelta.x += rotatableMove.x; - moveDelta.y += rotatableMove.y; - if (moveDelta.x == 0 && moveDelta.y == 0) { - if(fireAnimationQueue) { - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.rotate); - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.move); - } - if (completionCallback) completionCallback(); - } else { - $jobj(id).animate({ top: '+=' + moveDelta.y, left: '+=' + moveDelta.x }, { - duration: duration, - easing: easing, - queue: false, - complete: function () { - if(fireAnimationQueue) { - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.move); - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.rotate); - } - if (completionCallback) completionCallback(); - } - }); - } - } - - - _move.circularMove = function (id, degreeDelta, centerPoint, moveDelta, rotatableMove, resizeOffset, options, fireAnimationQueue, completionCallback, willDoRotation) { - var elem = $jobj(id); - if(!willDoRotation) elem = $addAll(elem, id); - - var moveInfo = $ax.move.PrepareForMove(id, moveDelta.x, moveDelta.y, false, options); - // If not rotating, still need to check moveDelta and may need to handle that. - if (degreeDelta === 0) { - _noRotateOnlyMove(id, moveDelta, rotatableMove, fireAnimationQueue, options.easing, options.duration, completionCallback); - return; - } - - var stepFunc = function(newDegree) { - var deg = newDegree - rotation.degree; - var widgetCenter = $ax('#' + id).offsetBoundingRect().centerPoint; - //var widgetCenter = $ax.public.fn.getWidgetBoundingRect(id).centerPoint; - //console.log("widget center of " + id + " x " + widgetCenter.x + " y " + widgetCenter.y); - var widgetNewCenter = $axure.fn.getPointAfterRotate(deg, widgetCenter, centerPoint); - - // Start by getting the move not related to rotation, and make sure to update center point to move with it. - var ratio = deg / degreeDelta; - - var xdelta = (moveDelta.x + rotatableMove.x) * ratio; - var ydelta = (moveDelta.y + rotatableMove.y) * ratio; - if(resizeOffset) { - var resizeShift = {}; - resizeShift.x = resizeOffset.x * ratio; - resizeShift.y = resizeOffset.y * ratio; - $axure.fn.getPointAfterRotate(rotation.degree, resizeShift, { x: 0, y: 0 }); - xdelta += resizeShift.x; - ydelta += resizeShift.y; - } - centerPoint.x += xdelta; - centerPoint.y += ydelta; - - // Now for the move that is rotatable, it must be rotated - rotatableMove = $axure.fn.getPointAfterRotate(deg, rotatableMove, { x: 0, y: 0 }); - - // Now add in circular move to the mix. - xdelta += widgetNewCenter.x - widgetCenter.x; - ydelta += widgetNewCenter.y - widgetCenter.y; - - $ax.visibility.moveMovedLocation(id, xdelta, ydelta); - - if(xdelta < 0) elem.css('left', '-=' + -xdelta); - else if(xdelta > 0) elem.css('left', '+=' + xdelta); - - if(ydelta < 0) elem.css('top', '-=' + -ydelta); - else if(ydelta > 0) elem.css('top', '+=' + ydelta); - }; - - var onComplete = function() { - if(fireAnimationQueue) $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.move); - if(completionCallback) completionCallback(); - if(moveInfo.rootLayer) $ax.visibility.popContainer(moveInfo.rootLayer, false); - var isPercentWidthPanel = $ax.dynamicPanelManager.isPercentWidthPanel($obj(id)); - if(isPercentWidthPanel) { - $ax.dynamicPanelManager.updatePanelPercentWidth(id); - $ax.dynamicPanelManager.updatePanelContentPercentWidth(id); - } - if(elem.css('position') == 'fixed') { - if(!isPercentWidthPanel) elem.css('left', ''); - elem.css('top', ''); - } - }; - - var rotation = { degree: 0 }; - - if(!options.easing || options.easing === 'none' || options.duration <= 0) { - stepFunc(degreeDelta); - onComplete(); - } else { - $(rotation).animate({ degree: degreeDelta }, { - duration: options.duration, - easing: options.easing, - queue: false, - step: stepFunc, - complete: onComplete - }); - } - }; - - //rotate a widget by degree, center is 50% 50% - _move.rotate = function (id, degree, easing, duration, to, shouldFire, completionCallback) { - var currentDegree = _move.getRotationDegree(id); - if(to) degree = degree - currentDegree; - - if(degree === 0) { - if (shouldFire) $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.rotate); - return; - } - - var query = $jobj(id); - var stepFunc = function(now) { - var degreeDelta = now - rotation.degree; - var newDegree = currentDegree + degreeDelta; - query.css($ax.public.fn.setTransformHowever("rotate(" + newDegree + "deg)")); - currentDegree = newDegree; - }; - - var onComplete = function() { - if(shouldFire) { - $ax.action.fireAnimationFromQueue($ax.public.fn.compoundIdFromComponent(id), $ax.action.queueTypes.rotate); - } - if(completionCallback) completionCallback(); - - $ax.annotation.adjustIconLocation(id); - }; - - var rotation = { degree: 0 }; - - $ax.visibility.setRotatedAngle(id, currentDegree + degree); - - //if no animation, setting duration to 1, to prevent RangeError in rotation loops without animation - if(!easing || easing === 'none' || duration <= 0) { - stepFunc(degree); - onComplete(); - } else { - $(rotation).animate({ degree: degree }, { - duration: duration, - easing: easing, - queue: false, - step: stepFunc, - complete: onComplete - }); - } - }; - - _move.compoundRotateAround = function (id, degreeDelta, centerPoint, moveDelta, rotatableMove, resizeOffset, easing, duration, fireAnimationQueue, completionCallback) { - if (degreeDelta === 0) { - _noRotateOnlyMove($ax.public.fn.compoundIdFromComponent(id), moveDelta, rotatableMove, fireAnimationQueue, easing, duration, completionCallback, $ax.action.queueTypes.rotate); - return; - } - var elem = $jobj(id); - var rotation = { degree: 0 }; - - if (!easing || easing === 'none' || duration <= 0) { - duration = 1; - easing = 'linear'; //it doesn't matter anymore here... - } - - var originalWidth = $ax.getNumFromPx(elem.css('width')); - var originalHeight = $ax.getNumFromPx(elem.css('height')); - var originalLeft = $ax.getNumFromPx(elem.css('left')); - var originalTop = $ax.getNumFromPx(elem.css('top')); - - $(rotation).animate({ degree: degreeDelta }, { - duration: duration, - easing: easing, - queue: false, - step: function (newDegree) { - var transform = $ax.public.fn.transformFromElement(elem[0]); - var originalCenter = { x: originalLeft + 0.5 * originalWidth, y: originalTop + 0.5 * originalHeight}; - var componentCenter = { x: originalCenter.x + transform[4], y: originalCenter.y + transform[5] }; - var deg = newDegree - rotation.degree; - var ratio = deg / degreeDelta; - var xdelta = (moveDelta.x + rotatableMove.x) * ratio; - var ydelta = (moveDelta.y + rotatableMove.y) * ratio; - if (resizeOffset) { - var resizeShift = {}; - resizeShift.x = resizeOffset.x * ratio; - resizeShift.y = resizeOffset.y * ratio; - $axure.fn.getPointAfterRotate(rotation.degree, resizeShift, { x: 0, y: 0 }); - xdelta += resizeShift.x; - ydelta += resizeShift.y; - } - - var rotationMatrix = $ax.public.fn.rotationMatrix(deg); - var compositionTransform = $ax.public.fn.matrixMultiplyMatrix(rotationMatrix, - { m11: transform[0], m21: transform[1], m12: transform[2], m22: transform[3] }); - - //console.log("widget center of " + id + " x " + widgetCenter.x + " y " + widgetCenter.y); - var widgetNewCenter = $axure.fn.getPointAfterRotate(deg, componentCenter, centerPoint); - var newMatrix = $ax.public.fn.matrixString(compositionTransform.m11, compositionTransform.m21, compositionTransform.m12, compositionTransform.m22, - widgetNewCenter.x - originalCenter.x + xdelta, widgetNewCenter.y - originalCenter.y + ydelta); - elem.css($ax.public.fn.setTransformHowever(newMatrix)); - }, - complete: function () { - if (fireAnimationQueue) { - $ax.action.fireAnimationFromQueue(elem.parent()[0].id, $ax.action.queueTypes.rotate); - } - - if(completionCallback) completionCallback(); - } - }); - }; - - _move.getRotationDegreeFromElement = function(element) { - if(element == null) return NaN; - - var transformString = element.style['transform'] || - element.style['-o-transform'] || - element.style['-ms-transform'] || - element.style['-moz-transform'] || - element.style['-webkit-transform']; - - if(transformString) { - var rotateRegex = /rotate\(([-?0-9]+)deg\)/; - var degreeMatch = rotateRegex.exec(transformString); - if(degreeMatch && degreeMatch[1]) return parseFloat(degreeMatch[1]); - } - - if(window.getComputedStyle) { - var st = window.getComputedStyle(element, null); - } else { - console.log('rotation is not supported for ie 8 and below in this version of axure rp'); - return 0; - } - - var tr = st.getPropertyValue("transform") || - st.getPropertyValue("-o-transform") || - st.getPropertyValue("-ms-transform") || - st.getPropertyValue("-moz-transform") || - st.getPropertyValue("-webkit-transform"); - - if(!tr || tr === 'none') return 0; - var values = tr.split('(')[1]; - values = values.split(')')[0], - values = values.split(','); - - var a = values[0]; - var b = values[1]; - - var radians = Math.atan2(b, a); - if(radians < 0) { - radians += (2 * Math.PI); - } - - return radians * (180 / Math.PI); - }; - - _move.getRotationDegree = function(elementId) { - if($ax.public.fn.IsLayer($obj(elementId).type)) { - return $jobj(elementId).data('layerDegree'); - } - return _move.getRotationDegreeFromElement(document.getElementById(elementId)); - } -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/recording.js b/web/main/static/resources/scripts/axure/recording.js deleted file mode 100644 index f5fb140..0000000 --- a/web/main/static/resources/scripts/axure/recording.js +++ /dev/null @@ -1,94 +0,0 @@ -// ******* Recording MANAGER ******** // - -$axure.internal(function($ax) { - var _recording = $ax.recording = {}; - - $ax.recording.recordEvent = function(element, eventInfo, axEventObject, timeStamp) { - - var elementHtml = $jobj(element); - var className = elementHtml.attr('class'); - var inputValue; - - if(className === 'ax_checkbox') { - inputValue = elementHtml.find('#' + element + '_input')[0].checked; - eventInfo.inputType = className; - eventInfo.inputValue = inputValue; - } - - if(className === 'ax_text_field') { - inputValue = elementHtml.find('#' + element + '_input').val(); - eventInfo.inputType = className; - eventInfo.inputValue = inputValue; - } - - - var scriptId = $ax.repeater.getScriptIdFromElementId(element); - var diagramObjectPath = $ax.getPathFromScriptId(scriptId); - var form = { - recordingId: $ax.recording.recordingId, - elementID: element, - eventType: axEventObject.description, - 'eventInfo': eventInfo, - // eventObject: axEventObject, - 'timeStamp': timeStamp, - 'path': diagramObjectPath -// , -// 'trigger': function() { -// $ax.event.handleEvent(element, eventInfo, axEventObject); -// return false; -// } - }; - - $ax.messageCenter.postMessage('logEvent', form); - }; - - - $ax.recording.maybeRecordEvent = function(element, eventInfo, axEventObject, timeStamp) { - }; - - - $ax.recording.recordingId = ""; - $ax.recording.recordingName = ""; - - $ax.messageCenter.addMessageListener(function(message, data) { - if(message === 'startRecording') { - $ax.recording.maybeRecordEvent = $ax.recording.recordEvent; - $ax.recording.recordingId = data.recordingId; - $ax.recording.recordingName = data.recordingName; - } else if(message === 'stopRecording') { - $ax.recording.maybeRecordEvent = function(element, eventInfo, axEventObject, timeStamp) { - }; - - } - else if(message === 'playEvent') { - - var eventType = makeFirstLetterLower(data.eventType); - var inputElement; - - var dObj = data.element === '' ? $ax.pageData.page : $ax.getObjectFromElementId(data.element); - if(!data.axEventObject) { - data.axEventObject = dObj && dObj.interactionMap && dObj.interactionMap[eventType]; - } - - data.eventInfo.thiswidget = $ax.getWidgetInfo(data.element); - data.eventInfo.item = $ax.getItemInfo(data.element); - - if(data.eventInfo.inputType && data.eventInfo.inputType === 'ax_checkbox') { - inputElement = $jobj(data.element + '_input'); - inputElement[0].checked = data.eventInfo.inputValue; - } - - if(data.eventInfo.inputType && data.eventInfo.inputType === 'ax_text_field') { - inputElement = $jobj(data.element + '_input'); - inputElement.val(data.eventInfo.inputValue); - } - - $ax.event.handleEvent(data.element, data.eventInfo, data.axEventObject, false, true); - } - }); - - var makeFirstLetterLower = function(eventName) { - return eventName.substr(0, 1).toLowerCase() + eventName.substr(1); - }; - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/repeater.js b/web/main/static/resources/scripts/axure/repeater.js deleted file mode 100644 index 99ca1ea..0000000 --- a/web/main/static/resources/scripts/axure/repeater.js +++ /dev/null @@ -1,2413 +0,0 @@ - -// ******* Repeater MANAGER ******** // -$axure.internal(function($ax) { - var _repeaterManager = {}; - $ax.repeater = _repeaterManager; - - var _refreshType = _repeaterManager.refreshType = { - reset: 1, - persist: 2, - preEval: 3 - }; - - //This is a mapping of current editItems - var repeaterToEditItems = {}; - //This is a mapping of current filters - var repeaterToFilters = {}; - // This is a mapping of current sorts - var repeaterToSorts = {}; - // This is a mapping of repeater page info - var repeaterToPageInfo = {}; - - //Hopefully this can be simplified, but for now I think 3 are needed. - //This is the data set that is owned by this repeater. The repeater may or may not reference this data set, and others can reference it. - var repeaterToLocalDataSet = {}; - //This is the data set referenced by the repeater. It is not a copy of the local data set, but a reference to a local data set (or eventually a global data set could be referenced). - var repeaterToCurrentDataSet = {}; - //This is a copy of the current data set, that is replaced whenever a set or refresh is done. - var repeaterToActiveDataSet = {}; - var _loadRepeaters = function() { - $ax(function(obj) { - return $ax.public.fn.IsRepeater(obj.type); - }).each(function(obj, repeaterId) { - repeaterToLocalDataSet[repeaterId] = $ax.deepCopy(obj.data); - repeaterToLocalDataSet[repeaterId].props = obj.dataProps; - repeaterToEditItems[repeaterId] = []; - - _initPageInfo(obj, repeaterId); - - _setRepeaterDataSet(repeaterId, repeaterId); - var initialItemIds = obj.repeaterPropMap.itemIds; - for (var i = 0; i < initialItemIds.length; i++) $ax.addItemIdToRepeater(initialItemIds[i], repeaterId); - $ax.visibility.initRepeater(repeaterId); - }); - }; - _repeaterManager.loadRepeaters = _loadRepeaters; - - var fullRefresh = {}; - var repeatersReady = false; - var _initRepeaters = function () { - repeatersReady = true; - $ax(function(obj, repeaterId) { - return $ax.public.fn.IsRepeater(obj.type); - }).each(function(obj, repeaterId) { - _refreshRepeater(repeaterId, undefined, _refreshType.reset, !fullRefresh[repeaterId]); - //// Fix selected and default if necessary - //var states = obj.evaluatedStates[repeaterId]; - //if(!states) return; // If there are no evaluated states the repeater id key could not be mapped to an array of states. - - //for(var i = 0; i < states.length; i++) { - // var state = states[i]; - - // $ax.style.SetWidgetEnabled(state.id, true); // So selected will take place. If disabled, selected wouldn't happen. - // $ax.style.SetWidgetSelected(state.id, state.selected); - // $ax.style.SetWidgetEnabled(state.id, !state.disabled); - //} - }); - }; - _repeaterManager.initRefresh = _initRepeaters; - - var repeatersHaveNewDataSet = []; - var _setRepeaterDataSet = function(repeaterId, dataSetId) { - //TODO: No idea about how global data sets will be handled... - repeaterToCurrentDataSet[repeaterId] = repeaterToLocalDataSet[dataSetId]; - repeaterToActiveDataSet[repeaterId] = getActiveDataSet(repeaterId); - repeaterToFilters[repeaterId] = []; - repeaterToSorts[repeaterId] = []; - - - // Not using this currently - // if(repeatersHaveNewDataSet.indexOf(repeaterId) == -1) repeatersHaveNewDataSet[repeatersHaveNewDataSet.length] = repeaterId; - }; - _repeaterManager.setDataSet = _setRepeaterDataSet; - - var _refreshRepeater = function(repeaterId, eventInfo, refreshType, itemsPregen) { - if(!refreshType) refreshType = _refreshType.reset; // Set default - if(!repeatersReady) { - fullRefresh[repeaterId] = true; - return; - } - - // Reset selected/disabled dictionaries upon reset, if necessary (reset must, persist can't, and preeval doesn't care because it hasn't been set up yet. - if(refreshType == _refreshType.reset) $ax.style.clearStateForRepeater(repeaterId); - - // Don't show if you have a parent rdos thats limboed. - var rdoPath = $ax.getPathFromScriptId(repeaterId); - // Check each parent rdo through appropriate views to see if you are limboed - while (rdoPath.length > 0) { - if(!$ax.getScriptIdFromPath(rdoPath)) { - removeItems(repeaterId); - return; - } - - $ax.splice(rdoPath, rdoPath.length - 1, 1); - } - - $ax.action.refreshStart(repeaterId); - $ax.style.ClearCacheForRepeater(repeaterId); - - if($ax.visibility.limboIds[repeaterId]) { - removeItems(repeaterId); - $ax.dynamicPanelManager.fitParentPanel(repeaterId); - return; - } - - // Remove delete map if there is one at this point - if(eventInfo && eventInfo.repeaterDeleteMap) delete eventInfo.repeaterDeleteMap[repeaterId]; - var path = $ax.getPathFromScriptId(repeaterId); - path.pop(); - - if(eventInfo) { - eventInfo = $ax.eventCopy(eventInfo); - } - - var obj = $ax.getObjectFromScriptId(repeaterId); - var propMap = obj.repeaterPropMap; - - //If there is no wrap, then set it to be above the number of rows - var viewId = $ax.adaptive.currentViewId || ''; - var wrap = _getAdaptiveProp(propMap, 'wrap', viewId, repeaterId, obj); - var vertical = _getAdaptiveProp(propMap, 'vertical', viewId, repeaterId, obj); - //var offset = propMap[viewId]; - var offset = propMap[_getViewIdFromPageViewId(viewId, repeaterId, obj)]; - - // Right now pregen only works for default adaptive view - if(viewId) itemsPregen = false; - var orderedIds = []; - if(itemsPregen) { - var repeaterChildren = $jobj(repeaterId).children(); - // Start at 1 to skip script div child - for(var i = 1; i < repeaterChildren.length; i++) { - orderedIds.push(_getItemIdFromElementId($(repeaterChildren[i]).attr('id'))); - } - } else orderedIds = getOrderedIds(repeaterId, eventInfo); - var ids = []; - var background = _getAdaptiveProp(propMap, 'backColor', viewId, repeaterId, obj); - var hasAltColor = _getAdaptiveProp(propMap, 'hasAltColor', viewId, repeaterId, obj); - var altColor = hasAltColor ? _getAdaptiveProp(propMap, 'altColor', viewId, repeaterId, obj) : undefined; - var useAlt = false; - - if(itemsPregen) { - var start = 0; - var end = orderedIds.length; - } else { - var bounds = _getVisibleDataBounds(repeaterToPageInfo[repeaterId], itemsPregen ? obj.data.length : orderedIds.length); - start = bounds[0]; - end = bounds[1]; - } - - var repeaterObj = $jobj(repeaterId); - var preevalMap = {}; - - var shownCount = end - start; - var primaryCount = wrap == -1 ? shownCount : Math.min(shownCount, wrap); - var secondaryCount = wrap == -1 ? 1 : Math.ceil(shownCount / wrap); - var widthCount = vertical ? secondaryCount : primaryCount; - var heightCount = vertical ? primaryCount : secondaryCount; - var paddingTop = _getAdaptiveProp(propMap, 'paddingTop', viewId, repeaterId, obj); - var paddingLeft = _getAdaptiveProp(propMap, 'paddingLeft', viewId, repeaterId, obj); - var paddingY = paddingTop + _getAdaptiveProp(propMap, 'paddingBottom', viewId, repeaterId, obj); - var paddingX = paddingLeft + _getAdaptiveProp(propMap, 'paddingRight', viewId, repeaterId, obj); - - var spacingX = _getAdaptiveProp(propMap, 'horizontalSpacing', viewId, repeaterId, obj); - var xOffset = offset.width + spacingX; - var spacingY = _getAdaptiveProp(propMap, 'verticalSpacing', viewId, repeaterId, obj); - var yOffset = offset.height + spacingY; - var repeaterSize = { width: paddingX, height: paddingY }; - repeaterSize.width += offset.width + (widthCount - 1) * xOffset; - repeaterSize.height += offset.height + (heightCount - 1) * yOffset; - $ax.visibility.setResizedSize(repeaterId, repeaterSize.width, repeaterSize.height); - - if(itemsPregen) { - var templateIds = [repeaterId]; - var processScriptIds = function (full, prop, id) { - if(id.indexOf('_') <= 0 && id.indexOf('p') == -1) templateIds.push('u' + id); - }; - $('#' + repeaterId + '_script').html().replace(/(id|for)="?u([0-9]+(p([0-9]){3})?(_[_a-z0-9]*)?)"?/g, processScriptIds); - for(var i = 0; i < templateIds.length; i++) { - for(var j = 0; j < orderedIds.length; j++) { - ids.push(_createElementId(templateIds[i], orderedIds[j])); - } - } - - for(var pos = start; pos < end; pos++) { - var itemId = orderedIds[pos]; - itemElementId = _createElementId(repeaterId, itemId); - var jobj = $jobj(itemElementId); - if(jobj.hasClass('preeval')) refreshType = _refreshType.preEval; - for(var i = 0; i < templateIds.length; i++) $ax.initializeObjectEvents($ax('#' + _createElementId(templateIds[i], itemId)), refreshType); - if(refreshType == _refreshType.preEval) { - preevalMap[itemId] = true; - jobj.removeClass('preeval'); - } - - $ax.visibility.setResizedSize(itemElementId, $ax.getNumFromPx(jobj.css('width')), $ax.getNumFromPx(jobj.css('height'))); - $ax.visibility.setMovedLocation(itemElementId, $ax.getNumFromPx(jobj.css('left')), $ax.getNumFromPx(jobj.css('top'))); - } - } else { - var html = $('#' + repeaterId + '_script').html(); - - var div = $('<div></div>'); - div.html(html); - div.find('.' + $ax.visibility.HIDDEN_CLASS).removeClass($ax.visibility.HIDDEN_CLASS); - div.find('.' + $ax.visibility.UNPLACED_CLASS).removeClass($ax.visibility.UNPLACED_CLASS); - div.css({ - width: offset.width, - height: offset.height - }); - - _applyColorCss(background, div); - var altDiv = div; - if(hasAltColor) altDiv = _applyColorCss(altColor, div.clone()); - - // Hide repeater, if shown, while updating. - var shown = $ax.visibility.IsIdVisible(repeaterId); - if(shown) document.getElementById(repeaterId).style.visibility = 'hidden'; - - //clean up old items as late as possible - removeItems(repeaterId); - resetItemSizes(repeaterId, offset, bounds, orderedIds, vertical, wrap); - - var i = 0; - var startTop = paddingTop; - var startLeft = paddingLeft; - if(repeaterObj.css('box-sizing') == 'border-box') { - startTop -= $ax.getNumFromPx(repeaterObj.css('border-top-width')) || 0; - startLeft -= $ax.getNumFromPx(repeaterObj.css('border-left-width')) || 0; - } - var top = startTop; - var left = startLeft; - for(pos = start; pos < end; pos++) { - itemId = orderedIds[pos]; - - var itemElementId = _createElementId(repeaterId, itemId); - $ax.addItemIdToRepeater(itemId, repeaterId); - - ids.push(itemElementId); - var processId = function(full, prop, id) { - var elementId = _createElementId('u' + id, itemId); - //If there is a suffix (ex. _img), then don't push the id. - if (id.indexOf('_') <= 0 && id.indexOf('p') == -1) ids.push(elementId); - return prop + '="' + elementId + '"'; - }; - - var copy = (useAlt ? altDiv : div).clone(); - useAlt = !useAlt; - copy.attr('id', itemElementId); - copy.html(div.html().replace(/(id|for)="?u([0-9]+(p([0-9]){3})?(_[_a-z0-9]*)?)"?/g, processId)); - if(obj.repeaterPropMap.isolateRadio) { - var radioButtons = copy.find(':radio'); - for(var radioIndex = 0; radioIndex < radioButtons.length; radioIndex++) { - var radio = $(radioButtons[radioIndex]); - var oldName = radio.attr('name') || ''; - // Can't use create element id because there could be an underscore in name - if(oldName) radio.attr('name', oldName + '-' + itemId); - } - } - - - copy.css({ - 'position': 'absolute', - 'top': top + 'px', - 'left': left + 'px', - 'width': obj.width + 'px', - 'height': obj.height + 'px' - }); - $('#' + repeaterId).append(copy); - $ax.visibility.setResizedSize(itemElementId, offset.width, offset.height); - $ax.visibility.setMovedLocation(itemElementId, left, top); - - i++; - if(wrap != -1 && i % wrap == 0) { - if(vertical) { - top = startTop; - left += xOffset; - } else { - left = startLeft; - top += yOffset; - } - } else if (vertical) top += yOffset; - else left += xOffset; - } - - repeaterObj.css(repeaterSize); - - // Had to move this here because it sets up cursor: pointer on inline links, - // but must be done before style cached when adaptive view is set. - // TODO: Should be able to combine this with initialization done in pregen items. Just need to have ids and template ids be the same. - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var childJobj = $jobj(id); - if (obj.repeaterPropMap.isolateSelection && childJobj.attr('selectiongroup')) { - childJobj.attr('selectiongroup', _createElementId(childJobj.attr('selectiongroup'), _getItemIdFromElementId(id))); - } - $ax.initializeObjectEvents($ax('#' + id), refreshType); - } - } - - var query = _getItemQuery(repeaterId); - if(viewId) $ax.adaptive.applyView(viewId, query); - else $ax.visibility.resetLimboAndHiddenToDefaults(_getItemQuery(repeaterId, preevalMap)); - - $ax.annotation.createFootnotes(query, true); - - for(var index = 0; index < ids.length; index++) { - id = ids[index]; - - if ($ax.ieColorManager) $ax.ieColorManager.applyBackground($ax('#' + id)); - //$ax.style.initializeObjectTextAlignment($ax('#' + id)); - $ax.applyHighlight($ax('#' + id), true); - } - - $ax.messageCenter.startCombineEventMessages(); - $ax.cacheRepeaterInfo(repeaterId, $ax.getWidgetInfo(repeaterId)); - - //$ax.style.startSuspendTextAlignment(); - // Now load - for(pos = start; pos < end; pos++) { - itemId = orderedIds[pos]; - itemElementId = _createElementId(repeaterId, itemId); - if(!preevalMap[orderedIds[pos]]) $ax.event.raiseSyntheticEvent(itemElementId, 'onItemLoad', true); - $ax.loadDynamicPanelsAndMasters(obj.objects, path, itemId); - } - //$ax.style.resumeSuspendTextAlignment(); - - $ax.removeCachedRepeaterInfo(repeaterId); - $ax.messageCenter.endCombineEventMessages(); - - // Reshow repeater if it was originally shown (load is complete by now) - if(shown && !itemsPregen) document.getElementById(repeaterId).style.visibility = 'inherit'; - - $ax.dynamicPanelManager.fitParentPanel(repeaterId); - - // Need to reapply the state style after refresh for text styles, and for applying a non-default style that wasn't reset for certain refreshes (adaptive changed for example). This could be way more selective but doing a safe change for the moment - if(refreshType != _refreshType.preEval) $ax.style.updateStateClass(repeaterId); - - // Right now we assume only one refresh at a time. If we can manually trigger refreshes, that may possibly change. - $ax.action.refreshEnd(); - }; - _repeaterManager.refreshRepeater = _refreshRepeater; - - _getRepeaterElementOffset = _repeaterManager.getRepeaterElementOffset = function (repeaterId, elementId) { - var viewId = $ax.adaptive.currentViewId || ''; - var robj = $ax.getObjectFromScriptId(repeaterId); - - var propMap = robj.repeaterPropMap; - var vertical = _getAdaptiveProp(propMap, 'vertical', viewId, repeaterId, robj); - var wrap = _getAdaptiveProp(propMap, 'wrap', viewId, repeaterId, robj); - var shownCount = propMap.itemIds.length; - var primaryCount = wrap == -1 ? shownCount : Math.min(shownCount, wrap); - var secondaryCount = wrap == -1 ? 1 : Math.ceil(shownCount / wrap); - var widthCount = vertical ? secondaryCount : primaryCount; - var heightCount = vertical ? primaryCount : secondaryCount; - var repeaterObj = $jobj(repeaterId); - var repeaterOffset = { x: $ax.getNumFromPx(repeaterObj.css('left')), y: $ax.getNumFromPx(repeaterObj.css('top')) }; - var paddingTop = _getAdaptiveProp(propMap, 'paddingTop', viewId, repeaterId, robj); - var paddingLeft = _getAdaptiveProp(propMap, 'paddingLeft', viewId, repeaterId, robj); - var offset = propMap[_getViewIdFromPageViewId(viewId, repeaterId, robj)]; - var spacingX = _getAdaptiveProp(propMap, 'horizontalSpacing', viewId, repeaterId, robj); - var xOffset = offset.width + spacingX; - var spacingY = _getAdaptiveProp(propMap, 'verticalSpacing', viewId, repeaterId, robj); - var yOffset = offset.height + spacingY; - - //first symbol after '-' - var repeaterNumber = elementId.split('-')[1][0]; - var elementIndex = 0; - while (propMap.itemIds[elementIndex] != repeaterNumber) { - elementIndex++; - } - - var multiplier = { y: 0, x: 0 }; - if (vertical) { - multiplier.y = elementIndex % heightCount; - multiplier.x = Math.floor(elementIndex / heightCount); - - } else { - multiplier.y = Math.floor(elementIndex / widthCount); - multiplier.x = elementIndex % widthCount; - } - - var firstTopLeftOffset = { x: paddingLeft + repeaterOffset.x, y: paddingTop + repeaterOffset.y }; - - var fitToContentOffset = { x: 0, y: 0 }; - - var elementContainerId = repeaterId + '-' + repeaterNumber; - var elementContainerDomElement = document.getElementById(elementContainerId); - if (elementContainerDomElement.style.top) { - fitToContentOffset.y = paddingTop + multiplier.y * yOffset - $ax.getNumFromPx(elementContainerDomElement.style.top); - } - if (elementContainerDomElement.style.left) { - fitToContentOffset.x = paddingLeft + multiplier.x * xOffset - $ax.getNumFromPx(elementContainerDomElement.style.left); - } - - return { - y: firstTopLeftOffset.y + multiplier.y * yOffset - fitToContentOffset.y, - x: firstTopLeftOffset.x + multiplier.x * xOffset - fitToContentOffset.x, - }; - } - - var _getItemQuery = function(repeaterId, preevalMap) { - var query = $ax(function (diagramObject, elementId) { - // Also need to check that this in not preeval - if(preevalMap) { - var itemId = _getItemIdFromElementId(elementId); - if(preevalMap[itemId]) return false; - } - - // All objects with the repeater as their parent, except the repeater itself. - var scriptId = _getScriptIdFromElementId(elementId); - return $ax.getParentRepeaterFromScriptId(scriptId) == repeaterId && scriptId != repeaterId; - }); - - return query; - } - - _repeaterManager.refreshAllRepeaters = function() { - $ax('*').each(function(diagramObject, elementId) { - if(!$ax.public.fn.IsRepeater(diagramObject.type)) return; - if($ax.visibility.isElementIdLimboOrInLimboContainer(elementId)) return; - _initPageInfo(diagramObject, elementId); - _refreshRepeater(elementId, $ax.getEventInfoFromEvent($ax.getjBrowserEvent()), _refreshType.persist); - }); - }; - - _repeaterManager.refreshRepeaters = function(ids, eventInfo) { - for(var i = 0; i < ids.length; i++) _refreshRepeater(ids[i], eventInfo); - }; - - var _initPageInfo = function(obj, elementId) { - var pageInfo = {}; - var map = obj.repeaterPropMap; - - var currentViewId = $ax.adaptive.currentViewId || ''; - var itemsPerPage = _getAdaptiveProp(map, 'itemsPerPage', currentViewId, elementId, obj); - if(itemsPerPage == -1) pageInfo.noLimit = true; - else { - pageInfo.itemsPerPage = itemsPerPage; - pageInfo.currPage = _getAdaptiveProp(map, 'currPage', currentViewId, elementId, obj); - } - repeaterToPageInfo[elementId] = pageInfo; - }; - - _repeaterManager.initialize = function() { - $ax(function (obj) { - return $ax.public.fn.IsRepeater(obj.type); - }).each(function (obj, repeaterId) { - _initPregen(repeaterId); - }); - } - - var _initPregen = function(repeaterId) { - var obj = $ax.getObjectFromScriptId(repeaterId); - var propMap = obj.repeaterPropMap; - - //If there is no wrap, then set it to be above the number of rows - var viewId = $ax.adaptive.currentViewId || ''; - var wrap = _getAdaptiveProp(propMap, 'wrap', viewId, repeaterId, obj); - var vertical = _getAdaptiveProp(propMap, 'vertical', viewId, repeaterId, obj); - - var orderedIds = []; - var ids = []; - var background = _getAdaptiveProp(propMap, 'backColor', viewId, repeaterId, obj); - var hasAltColor = _getAdaptiveProp(propMap, 'hasAltColor', viewId, repeaterId, obj); - var altColor = hasAltColor ? _getAdaptiveProp(propMap, 'altColor', viewId, repeaterId, obj) : undefined; - var useAlt = false; - - var bounds = _getVisibleDataBounds(repeaterToPageInfo[repeaterId], obj.data.length); - var start = bounds[0]; - var end = bounds[1]; - - // Starts empty - if(start == end) { - $ax.action.refreshEnd(repeaterId); - return; - } - var unprocessedBaseIds = $jobj($ax.repeater.createElementId(repeaterId, start + 1)).html().match(/(id|for)="?u([0-9]+)/g); - var baseIds = []; - if(unprocessedBaseIds) { - for(var i = 0; i < unprocessedBaseIds.length; i++) { - var val = unprocessedBaseIds[i].split('=')[1].substr(1); - if(baseIds.indexOf(val) == -1) baseIds.push(val); - } - } - - for(var itemNum = start; itemNum < end; itemNum++) { - ids.push($ax.repeater.createElementId(repeaterId, itemNum + 1)); - for(i = 0; i < baseIds.length; i++) ids.push($ax.repeater.createElementId(baseIds[i], itemNum + 1)); - var itemId = itemNum + 1; - orderedIds[itemNum] = itemId; - - var itemDiv = $jobj($ax.repeater.createElementId(repeaterId, itemNum + 1)); - _applyColorCss(useAlt ? altColor : background, itemDiv); - if(hasAltColor) useAlt = !useAlt; - } - - resetItemSizes(repeaterId, undefined, bounds, orderedIds, vertical, wrap); - }; - - var _applyColorCss = function(json, div) { - var args = json.r + ', ' + json.g + ', ' + json.b; - var background = json.a == 0 ? '' : json.a == 1 ? 'rgb(' + args + ')' : 'rgba(' + args + ', ' + json.a + ')'; - if($ax.ieColorManager && json.a != 0 && json.a != 1) { - var ieColor = $ax.ieColorManager.getColorFromArgb(json.a * 255, json.r, json.g, json.b, true); - if(ieColor) background = ieColor; - } - div.css('background-color', background); - return div; - }; - - var _getViewIdFromPageViewId = function (pageViewId, id, diagramObject) { - if (diagramObject.owner.type != 'Axure:Master') { - return pageViewId; - } else { - var parentRdoId = $ax('#' + id).getParents(true, ['rdo'])[0][0]; - var rdoState = $ax.style.generateState(parentRdoId); - var rdoStyle = $ax.style.computeFullStyle(parentRdoId, rdoState, pageViewId); - var viewOverride = rdoStyle.viewOverride; - return viewOverride; - } - } - - var _getAdaptiveProp = _repeaterManager.getAdaptiveProp = function (map, prop, viewId, repeaterId, repeaterObj) { - var viewChain = $ax.style.getViewIdChain(viewId, repeaterId, repeaterObj); - - for(var i = viewChain.length - 1; i >= 0; i--) { - viewId = viewChain[i]; - var viewProps = map[viewId]; - if(viewProps.hasOwnProperty(prop)) return viewProps[prop]; - } - - var base = repeaterObj.owner.type != 'Axure:Master' ? map[''] : map['19e82109f102476f933582835c373474']; - if(base.hasOwnProperty(prop)) return base[prop]; - return map['default'][prop]; - }; - - _repeaterManager.getItemCount = function(repeaterId) { - var data = repeaterToActiveDataSet[repeaterId].length; - var info = repeaterToPageInfo[repeaterId]; - if(!info.noLimit) { - var start = Math.min(data, info.itemsPerPage * info.currPage); - var end = Math.min(data, start + info.itemsPerPage); - data = end - start; - } - return data; - }; - - _repeaterManager.setDisplayProps = function(obj, repeaterId, itemIndex) { - var data = repeaterToActiveDataSet[repeaterId]; - var info = repeaterToPageInfo[repeaterId]; - var start = 0; - var end = data.length; - if(!info.noLimit) { - start = Math.min(end, info.itemsPerPage * (info.currPage - 1)); - end = Math.min(end, start + info.itemsPerPage); - } - var count = end - start; - var index = -1; - for(var i = 0; i < count; i++) { - if(data[start + i].index == itemIndex) index = i + 1; - } - if(index == -1) return; - obj.index = index; - obj.isfirst = index == 1; - obj.islast = index == end - start; - obj.iseven = index % 2 == 0; - obj.isodd = index % 2 == 1; - }; - - var _getVisibleDataBounds = function(pageInfo, count) { - var retval = [0, count]; - if(!pageInfo.noLimit) { - var end = pageInfo.itemsPerPage * pageInfo.currPage; - var start = end - pageInfo.itemsPerPage; - - // If past the end, move to last page - if(start >= count) { - pageInfo.currPage = Math.floor((count - 1) / pageInfo.itemsPerPage) + 1; - if(pageInfo.currPage <= 0) pageInfo.currPage = 1; - - end = pageInfo.itemsPerPage * pageInfo.currPage; - start = end - pageInfo.itemsPerPage; - } - end = Math.min(end, count); - retval[0] = start; - retval[1] = end; - } - return retval; - }; - - _repeaterManager.getVisibleDataCount = function(repeaterId) { - var bounds = _getVisibleDataBounds(repeaterToPageInfo[repeaterId], repeaterToActiveDataSet[repeaterId].length); - return bounds[1] - bounds[0]; - }; - - _repeaterManager.getDataCount = function(repeaterId) { - return repeaterToCurrentDataSet[repeaterId].length; - }; - - var _getFilteredDataCount = _repeaterManager.getFilteredDataCount = function(repeaterId) { - return repeaterToActiveDataSet[repeaterId].length; - }; - - _repeaterManager.getPageCount = function(repeaterId) { - var info = repeaterToPageInfo[repeaterId]; - return info.noLimit ? 1 : Math.ceil(_getFilteredDataCount(repeaterId) / info.itemsPerPage); - }; - - _repeaterManager.getPageIndex = function(repeaterId) { - var info = repeaterToPageInfo[repeaterId]; - return info.noLimit ? 1 : info.currPage; - }; - - var getActiveDataSet = function(repeaterId) { - var active = $ax.deepCopy(repeaterToCurrentDataSet[repeaterId]); - // Set up 1 indexing each item. - for(var i = 0; i < active.length; i++) active[i].index = i + 1; - return active; - }; - - var getOrderedIds = function(repeaterId, eventInfo) { - var data = repeaterToActiveDataSet[repeaterId] = getActiveDataSet(repeaterId); - - // Filter first so less to sort - applyFilter(repeaterId, data, eventInfo); - - // Sort next - var sorts = repeaterToSorts[repeaterId] || []; - if(sorts.length != 0 && data.length > 1) { - // TODO: Make this generic and factor out if we want to use it elsewhere... - // Compare is a function that takes 2 arguments, and returns a number. A high number means the second should go first - // Otherwise the first stays first. - var mergesort = function(list, start, end, compare) { - var middle = Math.floor((start + end) / 2); - if(middle - start > 1) mergesort(list, start, middle, compare); - if(end - middle > 1) mergesort(list, middle, end, compare); - var index1 = start; - var index2 = middle; - var tempList = []; - while(index1 < middle && index2 < end) { - tempList[tempList.length] = list[compare(list[index1], list[index2]) > 0 ? index2++ : index1++]; - } - while(index1 < middle) tempList[tempList.length] = list[index1++]; - while(index2 < end) tempList[tempList.length] = list[index2++]; - - // transfer from temp list to the real list. - for(var i = 0; i < tempList.length; i++) list[start + i] = tempList[i]; - }; - // Compare is the tie breaking function to us if necessary. - var getComparator = function(columnName, ascending, type, compare) { - // If this needs to be sped up, break up into several smaller functions conditioned off of type - return function(row1, row2) { - // If column undefined have it be empty string, NaN, or invalid date - //// If column undefined, no way to measure this, so call it a tie. - //if(row1[columnName] === undefined || row2[columnName] === undefined) return 0; - - var text1 = (row1[columnName] && row1[columnName].text) || ''; - var text2 = (row2[columnName] && row2[columnName].text) || ''; - - // This means we are case insensitive, so lowercase everything to kill casing - if(type == 'Text') { - text1 = text1.toLowerCase(); - text2 = text2.toLowerCase(); - } - - //If tied, go to tie breaker - if(text1 == text2) { - if(compare) return compare(row1, row2); - // Actually a tie. - return 0; - } - if(type == 'Text' || type == 'Text (Case Sensitive)') { - if(text1 < text2 ^ ascending) return 1; - else return -1; - } else if(type == 'Number') { - var num1 = text1 == '' ? NaN : Number(text1); - var num2 = text2 == '' ? NaN : Number(text2); - - if(isNaN(num1) && isNaN(num2)) return 0; - if(isNaN(num1) || isNaN(num2)) return isNaN(num1) ? 1 : -1; - if(num1 < num2 ^ ascending) return 1; - else return -1; - } else if(type == 'Date - YYYY-MM-DD' || type == 'Date - MM/DD/YYYY') { - var func = type == 'Date - YYYY-MM-DD' ? getDate1 : getDate2; - var date1 = func(text1); - var date2 = func(text2); - if(!date1.valid && !date2.valid) return 0; - if(!date1.valid || !date2.valid) return date1.valid ? -1 : 1; - var diff = date2.year - date1.year; - if(diff == 0) diff = date2.month - date1.month; - if(diff == 0) diff = date2.day - date1.day; - if(diff == 0) return 0; - return diff > 0 ^ ascending ? 1 : -1; - } - console.log('unhandled sort type'); - return 0; - }; - }; - var compareFunc = null; - for(var i = 0; i < sorts.length; i++) compareFunc = getComparator(sorts[i].columnName, sorts[i].ascending, sorts[i].sortType, compareFunc); - - mergesort(data, 0, data.length, compareFunc); - } - - var ids = []; - for(i = 0; i < data.length; i++) ids[i] = data[i].index; - - return ids; - }; - - var getDate1 = function(text) { - var date = { valid: false }; - var sections = text.split('-'); - if(sections.length == 1) sections = text.split('/'); - if(sections.length != 3) return date; - date.year = Number(sections[0]); - date.month = Number(sections[1]); - date.day = Number(sections[2]); - date.valid = !isNaN(date.year); - date.valid &= !isNaN(date.month) && date.month > 0 && date.month <= 12; - date.valid &= !isNaN(date.day) && date.day > 0 && date.day <= daysPerMonth(date.month, date.year); - return date; - }; - - var getDate2 = function(text) { - var date = { valid: false }; - var sections = text.split('-'); - if(sections.length == 1) sections = text.split('/'); - if(sections.length != 3) return date; - date.month = Number(sections[0]); - date.day = Number(sections[1]); - date.year = Number(sections[2]); - date.valid = !isNaN(date.year); - date.valid &= !isNaN(date.month) && date.month > 0 && date.month <= 12; - date.valid &= !isNaN(date.day) && date.day > 0 && date.day <= daysPerMonth(date.month, date.year); - return date; - }; - - var daysPerMonth = function(month, year) { - if(month == 9 || month == 4 || month == 6 || month == 11) return 30; - if(month != 2) return 31; - - if(year % 4 != 0) return 28; - if(year % 100 != 0) return 29; - return year % 400 == 0 ? 29 : 28; - }; - - var applyFilter = function(repeaterId, data, eventInfo) { - var dataFiltered = []; - var filters = repeaterToFilters[repeaterId] || []; - if (filters.length != 0) { - if(!eventInfo) eventInfo = $ax.getBasicEventInfo(); - var oldTarget = eventInfo.targetElement; - var oldSrc = eventInfo.srcElement; - var oldThis = eventInfo.thiswidget; - var oldItem = eventInfo.item; - - var idToWidgetInfo = {}; - - outer: - for(var i = 1; i <= data.length; i++) { - for(var j = 0; j < filters.length; j++) { - eventInfo.targetElement = _createElementId(repeaterId, i); - eventInfo.srcElement = filters[j].thisId; - if(!idToWidgetInfo[eventInfo.srcElement]) idToWidgetInfo[eventInfo.srcElement] = $ax.getWidgetInfo(eventInfo.srcElement); - eventInfo.thiswidget = idToWidgetInfo[eventInfo.srcElement]; - eventInfo.item = $ax.getItemInfo(eventInfo.srcElement); - - if($ax.expr.evaluateExpr(filters[j].filter, eventInfo) != 'true') continue outer; - } - dataFiltered[dataFiltered.length] = data[i - 1]; - } - - for(i = 0; i < dataFiltered.length; i++) data[i] = dataFiltered[i]; - while(data.length > dataFiltered.length) data.pop(); - - eventInfo.targetElement = oldTarget; - eventInfo.srcElement = oldSrc; - eventInfo.thiswidget = oldThis; - eventInfo.item = oldItem; - } - }; - - var _addFilter = function(repeaterId, removeOtherFilters, label, filter, thisId) { - if(removeOtherFilters) _removeFilter(repeaterId); - - var filterList = repeaterToFilters[repeaterId]; - if(!filterList) repeaterToFilters[repeaterId] = filterList = []; - - var filterObj = { filter: filter, thisId: thisId }; - if(label) filterObj.label = label; - filterList[filterList.length] = filterObj; - }; - _repeaterManager.addFilter = _addFilter; - - var _removeFilter = function(repeaterId, label) { - var filterList = repeaterToFilters[repeaterId]; - // If no list, nothing to remove - if(!filterList) return; - - // If no label, remove everything - if(!label) { - repeaterToFilters[repeaterId] = []; - return; - } - - for(var i = filterList.length - 1; i >= 0; i--) { - var filterObj = filterList[i]; - if(filterObj.label && filterObj.label == label) $ax.splice(filterList, i, 1); - } - }; - _repeaterManager.removeFilter = _removeFilter; - - var _addSort = function(repeaterId, label, columnName, ascending, toggle, sortType) { - var sortList = repeaterToSorts[repeaterId]; - if(!sortList) repeaterToSorts[repeaterId] = sortList = []; - - for(var i = 0; i < sortList.length; i++) { - if(columnName == sortList[i].columnName) { - var lastSortObj = $ax.splice(sortList, i, 1)[0]; - if(toggle) ascending = !lastSortObj.ascending; - break; - } - } - - var sortObj = { columnName: columnName, ascending: ascending, sortType: sortType }; - - if(label) sortObj.label = label; - sortList[sortList.length] = sortObj; - }; - _repeaterManager.addSort = _addSort; - - var _removeSort = function(repeaterId, label) { - var sortList = repeaterToSorts[repeaterId]; - // If no list, nothing to remove - if(!sortList) return; - - // If no label, remove everything - if(!label) { - repeaterToSorts[repeaterId] = []; - return; - } - - for(var i = sortList.length - 1; i >= 0; i--) { - var sortObj = sortList[i]; - if(sortObj.label && sortObj.label == label) $ax.splice(sortList, i, 1); - } - }; - _repeaterManager.removeSort = _removeSort; - - var _setRepeaterToPage = function(repeaterId, type, value, eventInfo) { - var pageInfo = repeaterToPageInfo[repeaterId]; - // page doesn't matter if there is no limit. - if(pageInfo.noLimit) return; - - var dataSet = repeaterToActiveDataSet[repeaterId]; - if(!dataSet) dataSet = repeaterToCurrentDataSet[repeaterId]; - var lastPage = Math.max(1, Math.ceil(dataSet.length / pageInfo.itemsPerPage)); - - if(type == 'Value') { - var val = Number($ax.expr.evaluateExpr(value, eventInfo)); - // if invalid, default to 1, otherwise, clamp the value - if(isNaN(val)) val = 1; - else if(val < 1) val = 1; - else if(val > lastPage) val = lastPage; - - pageInfo.currPage = val; - } else if(type == 'Previous') { - if(pageInfo.currPage > 1) pageInfo.currPage--; - } else if(type == 'Next') { - if(pageInfo.currPage < lastPage) pageInfo.currPage++; - } else if(type == 'Last') { - pageInfo.currPage = lastPage; - } else { - console.log('Unknown type'); - } - }; - _repeaterManager.setRepeaterToPage = _setRepeaterToPage; - - var _setNoItemLimit = function(repeaterId) { - var pageInfo = repeaterToPageInfo[repeaterId]; - delete pageInfo.currPage; - delete pageInfo.itemsPerPage; - pageInfo.noLimit = true; - }; - _repeaterManager.setNoItemLimit = _setNoItemLimit; - - var _setItemLimit = function(repeaterId, value, eventInfo) { - var pageInfo = repeaterToPageInfo[repeaterId]; - - if(pageInfo.noLimit) { - pageInfo.noLimit = false; - pageInfo.currPage = 1; - } - - var oldTarget = eventInfo.targetElement; - eventInfo.targetElement = repeaterId; - var itemLimit = Number($ax.expr.evaluateExpr(value, eventInfo)); - eventInfo.targetElement = oldTarget; - if(isNaN(itemLimit)) itemLimit = 20; - else if(itemLimit < 1) itemLimit = 1; - pageInfo.itemsPerPage = itemLimit; - }; - _repeaterManager.setItemLimit = _setItemLimit; - - var removeItems = function(repeaterId) { - var elementIds = $ax.getChildElementIdsForRepeater(repeaterId); - var itemId = $ax.getItemIdsForRepeater(repeaterId); - for(var i = 0; i < itemId.length; i++) $jobj(_createElementId(repeaterId, itemId[i])).remove(); - $ax.visibility.clearLimboAndHiddenIds(elementIds); - $ax.visibility.clearMovedAndResizedIds(elementIds); - $ax.clearItemsForRepeater(repeaterId); - }; - - var repeaterSizes = {}; - var resetItemSizes = function (repeaterId, itemSize, bounds, ids, vertical, wrap) { - var calcItem = !itemSize; - if(calcItem) itemSize = {}; - - var repeaterMap = {}; - repeaterMap.vert = vertical; - var sizesMap = {}; - var sizes = []; - var currSizes = wrap == -1 ? sizes : []; - for(var i = 0; i + bounds[0] < bounds[1]; i++) { - var itemId = ids[i + bounds[0]]; - if(calcItem) { - var itemJobj = $jobj(_createElementId(repeaterId, itemId)); - itemSize.width = $ax.getNumFromPx(itemJobj.css('width')); - itemSize.height = $ax.getNumFromPx(itemJobj.css('height')); - } - - var size = { itemId: itemId, width: itemSize.width, height: itemSize.height }; - currSizes.push(size); - sizesMap[size.itemId] = size; - if(currSizes.length == wrap) { - sizes.push(currSizes); - currSizes = []; - } - } - if (wrap != -1 && currSizes.length > 0) sizes.push(currSizes); - repeaterMap.sizes = sizes; - repeaterMap.sizesMap = sizesMap; - repeaterSizes[repeaterId] = repeaterMap; - }; - - _repeaterManager.getItemSize = function(repeaterId, itemId) { - var repeaterSize = repeaterSizes[repeaterId]; - if (!repeaterSize) return false; - return repeaterSize.sizesMap[itemId]; - } - - _repeaterManager.setItemSize = function (repeaterId, itemId, width, height) { - var repeaterSize = repeaterSizes[repeaterId]; - if(!repeaterSize) return false; - var size = repeaterSize.sizesMap[itemId]; - var deltaX = width - size.width; - var deltaY = height - size.height; - if(!deltaX && !deltaY) return false; - - repeaterSize.resized = true; - - if(deltaX) _pushItems(repeaterId, itemId, deltaX, false, true); - if(deltaY) _pushItems(repeaterId, itemId, deltaY, true, true); - - if(deltaX || deltaY) $ax.event.raiseSyntheticEvent(_createElementId(repeaterId, itemId), 'onItemResize'); - - return true; - } - - var _pushItems = _repeaterManager.pushItems = function (repeaterId, itemId, delta, vertical, suppressFire) { - if(delta == 0) return; - - // Update repeater item size - var prop = vertical ? 'height' : 'width'; - var itemElementId = _createElementId(repeaterId, itemId); - var itemObj = $jobj(itemElementId); - itemObj.css(prop, $ax.getNumFromPx(itemObj.css(prop)) + delta); - $ax.visibility.setResizedSize(itemElementId, $ax.getNumFromPx(itemObj.css('width')), $ax.getNumFromPx(itemObj.css('height'))); - - var repeaterObj = $jobj(repeaterId); - var repeaterMap = repeaterSizes[repeaterId]; - var sizes = repeaterMap.sizes; - var wrap = sizes[0].length != undefined; - var vert = repeaterMap.vert; - - // Not wrapping, has to push in primary direction - if (!wrap && vert != vertical) { - var before = 0; - var after = 0; - var limit = 0; - for(var i = 0; i < sizes.length; i++) { - var size = sizes[i]; - if(size.itemId == itemId) { - before = size[prop]; - size[prop] += delta; - after = size[prop]; - } else { - limit = limit ? Math.max(limit, size[prop]) : size[prop]; - } - } - - // Repeater delta is because an item can increase secondary direction, but if another item is already larger, then repeater size isn't effected. - var repeaterDelta = delta; - if(sizes.length != 1) { - if(after >= limit) repeaterDelta = after - Math.max(limit, before); - else if(before > limit) repeaterDelta = limit - before; - else repeaterDelta = 0; - } - - _updateRepeaterSize(prop, repeaterObj, repeaterDelta, vert); - - if(!suppressFire) $ax.event.raiseSyntheticEvent(_createElementId(repeaterId, itemId), 'onItemResize'); - return; - } - - var index = 0; - var index2 = 0; - // Get the indices first - if(wrap) { - outer: - for(; index < sizes.length; index++) { - var innerSizes = sizes[index]; - for(index2 = 0; index2 < innerSizes.length; index2++) if(innerSizes[index2].itemId == itemId) break outer; - } - } else { - for(; index < sizes.length; index++) if(sizes[index].itemId == itemId) break; - } - // Find out who is being pushed - var itemIdsEffected = []; - if (vert == vertical) { - // To check for repeater resize, non-wrap is easy, for wrap you have to see if your new size is enough to effect the size given other col/row sizes. - repeaterDelta = delta; - if(wrap && sizes.length > 1) { - var viewId = $ax.adaptive.currentViewId || ''; - var obj = $obj(repeaterId); - var spacing = _getAdaptiveProp(obj.repeaterPropMap, (vert ? 'vertical' : 'horizontal') + 'Spacing', viewId, repeaterId, obj); - for(i = 0; i < sizes.length; i++) { - var rowColSize = 0; - var rowCol = sizes[i]; - for(var j = 0; j < rowCol.length; j++) { - if(j != 0) rowColSize += spacing; - rowColSize += rowCol[j][prop]; - } - - if(i == index) { - before = rowColSize; - after = before + delta; - } else { - limit = limit ? Math.max(limit, rowColSize) : rowColSize; - } - } - - if(after >= limit) repeaterDelta = after - Math.max(limit, before); - else if (before > limit) repeaterDelta = limit - before; - else repeaterDelta = 0; - } - - if (repeaterDelta) { - _updateRepeaterSize(prop, repeaterObj, repeaterDelta, vert); - } - - // Done the hard part, calculating/updating new repeater size. Now just resize items and find what to push. - var array = wrap ? sizes[index] : sizes; - i = wrap ? index2 : index; - array[i][prop] += delta; - - for(i++; i < array.length; i++) itemIdsEffected.push(array[i].itemId); - } else { - // Secondary push is more interesting. See how much your primary row/column is already pushing, if that changes - // then effect all rows/columns after it - - // Get the biggest one in the current row/column, ignoring the one we're changing - var biggest = 0; - var currSizes = sizes[index]; - for(i = 0; i < currSizes.length; i++) { - if (i == index2) continue; - - biggest = Math.max(biggest, currSizes[i][prop]); - } - - var beforeSize = Math.max(biggest, currSizes[index2][prop]); - currSizes[index2][prop] += delta; - var afterSize = Math.max(biggest, currSizes[index2][prop]); - - // Nothing pushed/pulled - if (afterSize == beforeSize) return; - - for(i = index + 1; i < sizes.length; i++) { - currSizes = sizes[i]; - for(j = 0; j < currSizes.length; j++) itemIdsEffected.push(currSizes[j].itemId); - } - - // Delta is only how much the whole row/column changed - delta = afterSize - beforeSize; - - // Repeater resize secondary is determined by the effective delta. - _updateRepeaterSize(prop, repeaterObj, delta, vert); - } - - for(i = 0; i < itemIdsEffected.length; i++) { - var currItemId = itemIdsEffected[i]; - var elementId = _createElementId(repeaterId, currItemId); - var loc = vertical ? 'top' : 'left'; - var jobj = $jobj(elementId); - var currVal = $ax.getNumFromPx(jobj.css(loc)); - jobj.css(loc, currVal + delta); - $ax.visibility.setMovedLocation(elementId, $ax.getNumFromPx(jobj.css('left')), $ax.getNumFromPx(jobj.css('top'))); - } - - if(!suppressFire) $ax.event.raiseSyntheticEvent(_createElementId(repeaterId, itemId), 'onItemResize'); - } - - var _updateRepeaterSize = function(prop, jobj, delta, vert) { - if (delta == 0) return; - var val = $ax.getNumFromPx(jobj.css(prop)) + delta; - var border = 0; - if(vert) border += $ax.getNumFromPx(jobj.css('border-top-width')) + $ax.getNumFromPx(jobj.css('border-bottom-width')); - else border += $ax.getNumFromPx(jobj.css('border-left-width')) + $ax.getNumFromPx(jobj.css('border-right-width')); - val += border; - jobj.css(prop, val); - $ax.visibility.setResizedSize(jobj.attr('id'), $ax.getNumFromPx(jobj.css('width')), $ax.getNumFromPx(jobj.css('height'))); - $ax.dynamicPanelManager.fitParentPanel(jobj.attr('id')); - } - - var _getDataFromDataSet = function (eventInfo, repeaterId, itemId, propName, type) { - var row = undefined; - var deleteMap = eventInfo && eventInfo.repeaterDeleteMap && eventInfo.repeaterDeleteMap[repeaterId]; - if(deleteMap) row = deleteMap.idToRow[itemId]; - - if(!row) { - var itemNum = _getRealItemId(eventInfo, repeaterId, Number(itemId)); - row = repeaterToCurrentDataSet[repeaterId][itemNum]; - } - // Default to obj with text as empty string, as we don't generate the data for empty props - var data = row[propName] || { text: '' }; - //For now text is always the default. May change this to depend on context. - switch(type) { - case 'data': return data.type == 'text' ? data.text : data - case 'img': return (data.img && data.img[$ax.adaptive.getSketchKey()]) || data.text; - default: return (type && data[type]) || data.text; - } - //return type == 'data' && data.type != 'text' ? data : (type && data[type]) || data['text']; - }; - _repeaterManager.getData = _getDataFromDataSet; - - _repeaterManager.hasData = function(id, propName) { - if(!_getItemIdFromElementId(id)) return false; - var repeaterId = $ax.getParentRepeaterFromScriptId(_getScriptIdFromElementId(id)); - return Boolean(repeaterToCurrentDataSet[repeaterId] && repeaterToCurrentDataSet[repeaterId].props.indexOf(propName) != -1); - }; - - var _getEventDeleteData = function(eventInfo, repeaterId) { - var repeaterDeleteMap = eventInfo.repeaterDeleteMap; - if(!repeaterDeleteMap) repeaterDeleteMap = eventInfo.repeaterDeleteMap = {}; - - var myDeleteMap = repeaterDeleteMap[repeaterId]; - if(!myDeleteMap) { - myDeleteMap = repeaterDeleteMap[repeaterId] = {}; - myDeleteMap.deletedIds = []; - myDeleteMap.idToRow = {}; - } - - return myDeleteMap; - }; - - var _getRealItemId = function(eventInfo, repeaterId, itemId) { - var deletedBefore = 0; - var map = eventInfo.repeaterDeleteMap && eventInfo.repeaterDeleteMap[repeaterId]; - var deletedIds = map && map.deletedIds; - if(!deletedIds) return itemId - 1; - - for(var i = 0; i < deletedIds.length; i++) if (deletedIds[i] < itemId) deletedBefore++; - return itemId - deletedBefore - 1; - } - - var _addItemToDataSet = function(repeaterId, row, itemEventInfo) { - itemEventInfo.data = true; - var oldTarget = itemEventInfo.targetElement; - itemEventInfo.targetElement = repeaterId; - var dataSet = repeaterToLocalDataSet[repeaterId]; - - for(var propName in row) { - if(!row.hasOwnProperty(propName)) continue; - var prop = row[propName]; - if(prop.type == 'literal') { - var retval = $ax.expr.evaluateExpr(prop.literal, itemEventInfo); - if(typeof (retval) == 'string' || retval instanceof Date) retval = { type: 'text', text: retval }; - row[propName] = retval; - } - } - - itemEventInfo.targetElement = oldTarget; - dataSet[dataSet.length] = row; - itemEventInfo.data = false; - }; - _repeaterManager.addItem = _addItemToDataSet; - - var _deleteItemsFromDataSet = function(repeaterId, eventInfo, type, rule) { - var dataSet = repeaterToCurrentDataSet[repeaterId]; - var deleteDataMap = _getEventDeleteData(eventInfo, repeaterId); - var items; - - // Should always be this, marked, or rule. - if(type == 'this') items = [_getItemIdFromElementId(eventInfo.srcElement)]; - else if(type == 'marked') items = $ax.deepCopy(repeaterToEditItems[repeaterId]); - else { - // This should be rule - var visibleData = repeaterToCurrentDataSet[repeaterId]; - items = []; - var oldTarget = eventInfo.targetElement; - for(var i = 0; i < visibleData.length + deleteDataMap.deletedIds.length; i++) { - var index = i + 1; - if(deleteDataMap.deletedIds.indexOf(index) != -1) continue; - - eventInfo.targetElement = _createElementId(repeaterId, index); - if($ax.expr.evaluateExpr(rule, eventInfo).toLowerCase() != 'true') continue; - items.push(index); - } - eventInfo.targetElement = oldTarget; - } - // Want them decending - items.sort(function(a, b) { return b - a; }); - var editItems = repeaterToEditItems[repeaterId]; - - for(i = 0; i < items.length; i++) { - var itemId = items[i]; - - // Don't delete already deletedItem - if(deleteDataMap.deletedIds.indexOf(itemId) != -1) continue; - - var deletedRow = $ax.splice(dataSet, _getRealItemId(eventInfo, repeaterId, itemId), 1)[0]; - deleteDataMap.deletedIds.push(itemId); - deleteDataMap.idToRow[itemId] = deletedRow; - for(var j = editItems.length - 1; j >= 0; j--) { - var editItem = editItems[j]; - if(editItem == itemId) $ax.splice(editItems, j, 1); - else if(editItem > itemId) editItems[j] = editItem - 1; - } - } - }; - _repeaterManager.deleteItems = _deleteItemsFromDataSet; - - var _updateEditItemsInDataSet = function(repeaterId, propMap, eventInfo, type, rule) { - var oldTarget = eventInfo.targetElement; - var dataSet = repeaterToCurrentDataSet[repeaterId]; - var items; - - // Should always be this, marked, or rule. - if(type == 'this') items = [_getItemIdFromElementId(eventInfo.srcElement)]; - else if(type == 'marked') items = repeaterToEditItems[repeaterId]; - else { - // This should be rule - var currData = repeaterToCurrentDataSet[repeaterId]; - items = []; - oldTarget = eventInfo.targetElement; - for(var i = 0; i < currData.length; i++) { - var index = i + 1; - eventInfo.targetElement = _createElementId(repeaterId, index); - if($ax.expr.evaluateExpr(rule, eventInfo).toLowerCase() != 'true') continue; - items.push(index); - } - eventInfo.targetElement = oldTarget; - } - - eventInfo.data = true; - for(var prop in propMap) { - if(!propMap.hasOwnProperty(prop)) continue; - for(i = 0; i < items.length; i++) { - var data = propMap[prop]; - var item = items[i]; - if(data.type == 'literal') { - eventInfo.targetElement = _createElementId(repeaterId, item); - data = $ax.expr.evaluateExpr(data.literal, eventInfo); - if(typeof (data) == 'object' && data.isWidget) data = data.text; - if(typeof (data) == 'string') data = { type: 'text', text: data }; - } - dataSet[_getRealItemId(eventInfo, repeaterId, item)][prop] = data; - } - } - eventInfo.targetElement = oldTarget; - eventInfo.data = false; - }; - _repeaterManager.updateEditItems = _updateEditItemsInDataSet; - - var _getAllItemIds = function(repeaterId) { - var retval = []; - var currDataSet = repeaterToCurrentDataSet[repeaterId]; - for(var i = 0; i < currDataSet.length; i++) retval.push(i + 1); - return retval; - }; - _repeaterManager.getAllItemIds = _getAllItemIds; - - var _addEditItemToRepeater = function(repeaterId, itemIds) { - for(var i = 0; i < itemIds.length; i++) { - var itemId = Number(itemIds[i]); - var items = repeaterToEditItems[repeaterId]; - if(items.indexOf(itemId) == -1) items[items.length] = itemId; - } - }; - _repeaterManager.addEditItems = _addEditItemToRepeater; - - var _removeEditItemFromRepeater = function(repeaterId, itemIds) { - for(var i = 0; i < itemIds.length; i++) { - var itemId = itemIds[i]; - var items = repeaterToEditItems[repeaterId]; - var index = items.indexOf(Number(itemId)); - if(index != -1) $ax.splice(items, index, 1); - } - }; - _repeaterManager.removeEditItems = _removeEditItemFromRepeater; - - _repeaterManager.isEditItem = function(repeaterId, itemId) { - var items = repeaterToEditItems[repeaterId]; - return items.indexOf(Number(itemId)) != -1; - }; - - var _createElementId = function(scriptId, itemId) { - if(!itemId) return scriptId; - var i = scriptId.indexOf('_'); - var sections = i > -1 ? [scriptId.substring(0, i), scriptId.substring(i + 1)] : [scriptId]; - var retval = sections[0] + '-' + itemId; - return sections.length > 1 ? retval + '_' + sections[1] : retval; - }; - _repeaterManager.createElementId = _createElementId; - - var _getElementId = function(scriptId, childId) { - var elementId = scriptId; - if($ax.getParentRepeaterFromScriptId(scriptId)) { - // Must be in the same item as the child - var itemId = $ax.repeater.getItemIdFromElementId(childId); - elementId = $ax.repeater.createElementId(scriptId, itemId); - } - return elementId; - }; - _repeaterManager.getElementId = _getElementId; - - var _getScriptIdFromElementId = function(elementId) { - if(!elementId) return elementId; - var sections = elementId.split('-'); - var retval = sections[0]; - if(sections.length <= 1) return retval; - sections = sections[1].split('_'); - return sections.length > 1 ? retval + '_' + sections[1] : retval; - }; - _repeaterManager.getScriptIdFromElementId = _getScriptIdFromElementId; - - var _getItemIdFromElementId = function(elementId) { - var sections = elementId.split('-'); - if(sections.length < 2) return ''; - sections = sections[1].split('_'); - return sections[0]; - }; - _repeaterManager.getItemIdFromElementId = _getItemIdFromElementId; - - // TODO: Just inline this if we keep it this way. - var _applySuffixToElementId = function(id, suffix) { - return id + suffix; - // return _createElementId(_getScriptIdFromElementId(id) + suffix, _getItemIdFromElementId(id)); - }; - _repeaterManager.applySuffixToElementId = _applySuffixToElementId; - - var _removeSuffixFromElementId = function (id) { - var suffixId = id.indexOf('_'); - if(suffixId != -1) return id.substr(0, suffixId); - - var partId = id.indexOf('p'); - if(partId != -1) return _createElementId(id.substr(0, partId), _getItemIdFromElementId(id)); // item id is after part, but before suffix - - return id; - } - _repeaterManager.removeSuffixFromElementId = _removeSuffixFromElementId; - - // var _getRepeaterSize = function(repeaterId) { - // var itemCount = ($ax.getItemIdsForRepeater(repeaterId) || []).length; - // if(itemCount == 0) return { width: 0, height: 0 }; - - // var repeater = $obj(repeaterId); - // // Width and height per item; - // var width = repeater.width; - // var height = repeater.height; - - // var viewId = $ax.adaptive.currentViewId || ''; - // var widthIncrement = width + _getAdaptiveProp(repeater.repeaterPropMap, 'horizontalSpacing', viewId); - // var heightIncrement = height + _getAdaptiveProp(repeater.repeaterPropMap, 'verticalSpacing', viewId); - - // var wrap = _getAdaptiveProp(repeater.repeaterPropMap, 'wrap', viewId); - // var vertical = _getAdaptiveProp(repeater.repeaterPropMap, 'vertical', viewId); - - // if(wrap == -1 || itemCount <= wrap) { - // if(vertical) height += heightIncrement * (itemCount - 1); - // else width += widthIncrement * (itemCount - 1); - // } else { - // var primaryDim = wrap; - // var secondaryDim = Math.ceil(itemCount / primaryDim); - - // if(vertical) { - // height += heightIncrement * (primaryDim - 1); - // width += widthIncrement * (secondaryDim - 1); - // } else { - // width += widthIncrement * (primaryDim - 1); - // height += heightIncrement * (secondaryDim - 1); - // } - // } - // return { width: width, height: height }; - // }; - // _repeaterManager.getRepeaterSize = _getRepeaterSize; - -}); - -// ******* Dynamic Panel Manager ******** // -$axure.internal(function($ax) { - // TODO: Probably a lot of the dynamic panel functions from pagescript should be moved here at some point... - var _dynamicPanelManager = $ax.dynamicPanelManager = {}; - - var _isIdFitToContent = _dynamicPanelManager.isIdFitToContent = function(id) { - var obj = $obj(id); - if (!obj || !$ax.public.fn.IsDynamicPanel(obj.type) || !obj.fitToContent) return false; - - var jpanel = $jobj(id); - return !jpanel.attr('data-notfit'); - }; - - //this function fit parent panel, also check for parent layer or repeaters - var _fitParentPanel = function (widgetId) { - - var parentLayer = getParentLayer(widgetId); - if(parentLayer) { - if(_updateLayerRectCache(parentLayer)) _fitParentPanel(parentLayer); - return; - } - - // Find parent panel if there is one. - var parentPanelInfo = getParentPanel(widgetId); - if(parentPanelInfo) { - var parentId = parentPanelInfo.parent; - _updateMobileScroll(parentId, parentPanelInfo.stateId, true); - if(_updateFitPanel(parentId, parentPanelInfo.state)) _fitParentPanel(parentId); - return; - } - - // Otherwise, try to get parent repeater - var parentRepeaterId = $ax.getParentRepeaterFromElementId(widgetId); - var repeaterObj = $obj(parentRepeaterId); - if (repeaterObj && widgetId != parentRepeaterId && repeaterObj.repeaterPropMap.fitToContent) { - var itemId = $ax.repeater.getItemIdFromElementId(widgetId); - var containerId = $ax.repeater.createElementId(parentRepeaterId, itemId); - var childrenRect = $ax('#' + containerId).childrenBoundingRect(); - $ax.repeater.setItemSize(parentRepeaterId, itemId, childrenRect.right, childrenRect.bottom); - return; - } - - $ax.adaptive.updateMobileScrollOnBody(); - }; - _dynamicPanelManager.fitParentPanel = _fitParentPanel; - - var _updateMobileScroll = _dynamicPanelManager.updateMobileScroll = function (panelId, stateId, blockResetScroll) { - if (!panelId) return false; - - // Only update scroll if panel is scrollable - if ($ax.dynamicPanelManager.isIdFitToContent(panelId)) return false; - var obj = $obj(panelId); - if (!obj || obj.scrollbars.toLowerCase() == 'none') return false; - - var stateQuery = $jobj(stateId); - $ax.adaptive.removeNiceScroll(stateQuery, blockResetScroll); - - //check if the page is in mobile mode - if(!$ax.adaptive.isDeviceMode() || MOBILE_DEVICE) { - stateQuery.css('cursor', ''); - return false; - } - - var stateContentId = stateId + '_content'; - var childrenRect = $ax('#' + stateContentId).childrenBoundingRect(); - var size = { width: childrenRect.right, height: childrenRect.bottom }; - - var $stateContent = $('#' + stateContentId); - $stateContent.css({ 'height': size.height + 'px', 'width': size.width + 'px' }); - - // Apply niceScroll and update cursor - if (obj.isExpo) { - var headerHeight = obj.headerHeight ? obj.headerHeight : 0; - var footerHeight = obj.footerHeight ? obj.footerHeight : 0; - - $ax.adaptive.addNiceScroll(stateQuery, { emulatetouch: true, bouncescroll: false, grabcursorenabled: false, railmargin: { top: headerHeight, bottom: footerHeight }, scrollbarid: stateId + "-sb" }); - stateQuery.find('.nicescroll-rails').css('margin-top', headerHeight + 'px'); - } else { - $ax.adaptive.addNiceScroll(stateQuery, { emulatetouch: true, horizrailenabled: obj.scrollbars != 'verticalAsNeeded' }, blockResetScroll); - } - - stateQuery.css('cursor', 'url(resources/css/images/touch.cur), auto'); - stateQuery.css('cursor', 'url(resources/css/images/touch.svg) 32 32, auto'); - } - - _dynamicPanelManager.initMobileScroll = function () { - var scrollable = []; - $ax('*').each(function (obj, elementId) { - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - if ($ax.public.fn.IsDynamicPanel(obj.type) && obj.scrollbars != 'None' && obj.scrollbars != 'none' && !$ax.visibility.isElementIdLimboOrInLimboContainer(scriptId)) { - scrollable[scrollable.length] = elementId; - } - }); - for (var i = scrollable.length - 1; i >= 0; i--) { - var panelId = scrollable[i]; - var stateId = $ax.repeater.applySuffixToElementId(panelId, '_state0'); - _updateMobileScroll(panelId, stateId, true); - } - }; - - - _dynamicPanelManager.initialize = function() { - $axure.resize(_handleResize); - $(window).scroll(_handleScroll); - }; - - var percentPanelToLeftCache = []; - var percentPanelsInitialized = false; - var _handleResize = function() { - if(percentPanelsInitialized) { - for(var key in percentPanelToLeftCache) { - //could optimize to only update non-contained panels - _updatePanelPercentWidth(key); - } - } else { - $ax('*').each(function(obj, elementId) { - if(_isPercentWidthPanel(obj)) _updatePanelPercentWidth(elementId); - }); - percentPanelsInitialized = true; - } - _adjustFixedCenter(); - }; - - var _isPercentWidthPanel = _dynamicPanelManager.isPercentWidthPanel = function(obj) { - return obj && $ax.public.fn.IsDynamicPanel(obj.type) && obj.percentWidth; - }; - - _dynamicPanelManager.updatePanelContentPercentWidth = function(elementId) { - // if(_isPercentWidthPanel($obj(elementId))) return; - var stateChildrenQuery = $jobj(elementId).children('.panel_state'); - stateChildrenQuery.children('.panel_state_content').each( - function() { - $(this).children('.ax_dynamic_panel').each( - function() { _updatePanelPercentWidth(this.id); } - ); - } - ); - }; - - _dynamicPanelManager.updatePercentPanelCache = function(query) { - query.each(function(obj, elementId) { - if(_isPercentWidthPanel(obj)) { - if(_updatePercentPanelToLeftCache(obj, elementId, true)) { - _updatePanelPercentWidth(elementId); - } - } - }); - }; - - var _handleScroll = function () { - _adjustFixedCenter(); - }; - - var fixedCenterPanels = []; - var fixedCenterPanelsInitialized = false; - - var _adjustFixedCenter = function () { - - if (!fixedCenterPanelsInitialized) { - $axure(function(diagramObject) { - return diagramObject.fixedHorizontal && diagramObject.fixedHorizontal == 'center' && !diagramObject.percentWidth; - }) - .each(function (diagramObject, elementId) { - fixedCenterPanels.push(elementId); - }); - fixedCenterPanelsInitialized = true; - } - - for (var i = 0; i < fixedCenterPanels.length; i++) { - var elementId = fixedCenterPanels[i]; - var boundingRect = $ax('#' + elementId).offsetBoundingRect(); - var left = boundingRect.left; - - var win = $(window); - var winWidth = win.width(); - var elementQuery = $('#' + elementId); - - if (left >= 0 && winWidth >= boundingRect.width) { - elementQuery.css('left', '50%'); - continue; - } - - var leftMargin = $ax.getNumFromPx(elementQuery.css('margin-left')); - var newLeft = -leftMargin; - elementQuery.css('left', newLeft + 'px'); - } - }; - - _dynamicPanelManager.resetFixedPanel = function(obj, domElement) { - if(obj.fixedHorizontal == 'center') domElement.style.marginLeft = ""; - if(obj.fixedVertical == 'middle') domElement.style.marginTop = ""; - }; - - _dynamicPanelManager.resetAdaptivePercentPanel = function(obj, domElement) { - if(!_isPercentWidthPanel(obj)) return; - - if(obj.fixedHorizontal == 'center') domElement.style.marginLeft = ""; - else if(obj.fixedHorizontal == 'right') domElement.style.width = ""; - }; - - var _updatePercentPanelToLeftCache = function(obj, elementId, overwrite) { - var wasUpdated = false; - var jObj = $jobj(elementId); - var axObj = $ax('#' + elementId); - if(percentPanelToLeftCache[elementId] == undefined || overwrite) { - if (obj.fixedHorizontal == 'center') percentPanelToLeftCache[elementId] = $ax.getNumFromPx(jObj.css('margin-left')); - else if (obj.fixedHorizontal == 'right') percentPanelToLeftCache[elementId] = axObj.width() + $ax.getNumFromPx(jObj.css('right')); - else percentPanelToLeftCache[elementId] = $ax.getNumFromPx(jObj.css('left')); - wasUpdated = true; - } - - if(obj.fixedHorizontal == 'right' && _isIdFitToContent(elementId)) { - //var fitWidth = getContainerSize($ax.visibility.GetPanelState(elementId) + '_content').width; - var containerId = $ax.visibility.GetPanelState(elementId) + '_content'; - var childrenRect = $ax('#' + containerId).childrenBoundingRect(); - var fitWidth = childrenRect.right; - percentPanelToLeftCache[elementId] = fitWidth + $ax.getNumFromPx(jObj.css('right')); - wasUpdated = true; - } - return wasUpdated; - }; - - var _updatePanelPercentWidth = _dynamicPanelManager.updatePanelPercentWidth = function(elementId) { - var obj = $obj(elementId); - if(!_isPercentWidthPanel(obj)) return; - - _updatePercentPanelToLeftCache(obj, elementId, false); - - var width; - var x; - - if(obj.fixedHorizontal) { - x = 0; - width = $(window).width(); - } else { - var parentPanelInfo = getParentPanel(elementId); - if(parentPanelInfo) { - var parentId = parentPanelInfo.parent; - width = $ax('#' + parentId).width(); - var parentObj = $obj(parentId); - if(parentObj.percentWidth) { - var stateId = $ax.repeater.applySuffixToElementId(parentId, '_state' + parentPanelInfo.state); - var stateContentId = stateId + '_content'; - x = -$ax.getNumFromPx($jobj(stateContentId).css('margin-left')); - } else x = 0; - } else { - var parentRepeater = $ax.getParentRepeaterFromScriptId($ax.repeater.getScriptIdFromElementId(elementId)); - if(parentRepeater) { - var itemId = $ax.repeater.getItemIdFromElementId(elementId); - var itemContainerId = $ax.repeater.createElementId(parentRepeater, itemId); - x = 0; - width = $ax('#' + itemContainerId).width(); - } else { - var $window = $(window); - width = $window.width(); - var bodyLeft = $ax.getNumFromPx($('body').css('left')); - var bodyWidth = $ax.getNumFromPx($('body').css('width')); - var isCenter = $ax.adaptive.getPageStyle().pageAlignment == 'center'; - width = Math.max(width, bodyWidth); - x = isCenter ? -(width - bodyWidth) / 2 - bodyLeft : 0; - } - } - } - - var jObj = $jobj(elementId); - if(obj.fixedHorizontal == 'left') jObj.css('left', x + 'px'); - else if(obj.fixedHorizontal == 'center') { - jObj.css('left', x + 'px'); - jObj.css('margin-left', 0 + 'px'); - } else jObj.css('left', x + 'px'); - - jObj.css('width', width + 'px'); - - $ax.visibility.setResizedSize(elementId, width, $ax('#' + elementId).height()); - - var panelLeft = percentPanelToLeftCache[elementId]; - var stateParent = jObj; - while(stateParent.children()[0].id.indexOf($ax.visibility.CONTAINER_SUFFIX) != -1) stateParent = stateParent.children(); - var stateChildrenQuery = stateParent.children('.panel_state'); - stateChildrenQuery.css('width', width + 'px'); - - if(obj.fixedHorizontal == 'center') - stateChildrenQuery.children('.panel_state_content').css('left', '50%').css('margin-left', panelLeft + 'px'); - else if(obj.fixedHorizontal == 'right') - stateChildrenQuery.children('.panel_state_content').css('left', width - panelLeft + 'px'); - else stateChildrenQuery.children('.panel_state_content').css('margin-left', panelLeft - x + 'px'); - }; - - - _dynamicPanelManager.updateParentsOfNonDefaultFitPanels = function () { - $ax('*').each(function (diagramObject, elementId) { - if(!$ax.public.fn.IsDynamicPanel(diagramObject.type) || !diagramObject.fitToContent) return; - if($ax.visibility.isElementIdLimboOrInLimboContainer(elementId)) return; - - var stateId = $ax.visibility.GetPanelState(elementId); - if(stateId != $ax.repeater.applySuffixToElementId(elementId, '_state0')) _fitParentPanel(elementId); - }); - }; - - _dynamicPanelManager.updateAllLayerSizeCaches = function() { - var fitToContent = []; - var layers = []; - $ax('*').each(function (obj, elementId) { - var isLayer = $ax.public.fn.IsLayer(obj.type); - if(!isLayer) return; - if($ax.visibility.isElementIdLimboOrInLimboContainer(elementId)) return; - layers[layers.length] = elementId; - }); - for(var i = layers.length - 1; i >= 0; i--) { - var layerId = layers[i]; - _updateLayerRectCache(layerId); - } - }; - - //_dynamicPanelManager.updateAllFitPanelsAndLayerSizeCaches = function() { - // var fitToContent = []; - // var layers = []; - // $ax('*').each(function (obj, elementId) { - // var isFitPanel = $ax.public.fn.IsDynamicPanel(obj.type) && obj.fitToContent; - // var isLayer = $ax.public.fn.IsLayer(obj.type); - // if(!isFitPanel && !isLayer) return; - // if($ax.visibility.isElementIdLimboOrInLimboContainer(elementId)) return; - - // if(isFitPanel) { - // fitToContent[fitToContent.length] = elementId; - // } else if(isLayer) { - // layers[layers.length] = elementId; - // } - // }); - // for(var i = fitToContent.length - 1; i >= 0; i--) { - // var panelId = fitToContent[i]; - // var stateCount = $obj(panelId).diagrams.length; - // for(var j = 0; j < stateCount; j++) { - // $ax.dynamicPanelManager.setFitToContentCss(panelId, true); - // _updateFitPanel(panelId, j, true); - // } - // } - // for(var i = layers.length - 1; i >= 0; i--) { - // var layerId = layers[i]; - // _updateLayerSizeCache(layerId); - // } - //}; - - //var _getCachedLayerRect = function (elementId) { - // var element = document.getElementById(elementId); - // var rect = {}; - // rect.width = Number(element.getAttribute('data-width')); - // rect.height = Number(element.getAttribute('data-height')); - // rect.x = Number(element.getAttribute('data-left')); - // rect.y = Number(element.getAttribute('data-top')); - // return rect; - //} - - var _updateLayerRectCache = function (elementId) { - //var oldRect = _getCachedLayerRect(elementId); - - var axObj = $ax('#' + elementId); - var oldRect = axObj.offsetBoundingRect(); - - var childrenRect = axObj.childrenBoundingRect(); - var size = childrenRect.size; - var loc = childrenRect.location; - //var size = axObj.size(); - //var loc = {}; - //loc.x = axObj.locRelativeIgnoreLayer(false); - //loc.y = axObj.locRelativeIgnoreLayer(true); - - var sizeChange = oldRect.width != size.width || oldRect.height != size.height; - var locChange = oldRect.x != loc.x || oldRect.y != loc.y; - if(sizeChange || locChange) { - //var element = document.getElementById(elementId); - if(sizeChange) { - //element.setAttribute('data-width', size.width); - //element.setAttribute('data-height', size.height); - $ax.visibility.setResizedSize(elementId, size.width, size.height); - $ax.event.raiseSyntheticEvent(elementId, 'onResize'); - } - if(locChange) { - //element.setAttribute('data-left', loc.x); - //element.setAttribute('data-top', loc.y); - $ax.visibility.setMovedLocation(elementId, loc.x, loc.y); - $ax.event.raiseSyntheticEvent(elementId, 'onMove'); - } - return true; - } - return false; - } - - _dynamicPanelManager.setFitToContentCss = function(elementId, fitToContent, oldWidth, oldHeight) { - - if($ax.dynamicPanelManager.isIdFitToContent(elementId) == fitToContent) return; - - var panel = $jobj(elementId); - var stateCss; - var scrollbars = $obj(elementId).scrollbars; - - if(fitToContent) { - panel.attr('style', ''); - panel.removeAttr('data-notfit'); - stateCss = {}; - stateCss.position = 'relative'; - if(scrollbars != 'none') { - stateCss.overflow = 'visible'; - stateCss['-webkit-overflow-scrolling'] = 'visible'; - } - if(scrollbars == 'verticalAsNeeded') { - stateCss['overflow-x'] = 'visible'; - stateCss['-ms-overflow-x'] = 'visible'; - } else if(scrollbars == 'horizontalAsNeeded') { - stateCss['overflow-y'] = 'visible'; - stateCss['-ms-overflow-y'] = 'visible'; - } - panel.children().css(stateCss); - } else { - panel.attr('data-notfit', 'true'); - var panelCss = { width: oldWidth, height: oldHeight }; - stateCss = { width: oldWidth, height: oldHeight }; - panelCss.overflow = 'hidden'; - stateCss.position = 'absolute'; - if(scrollbars != 'none') { - stateCss.overflow = 'auto'; - stateCss['-webkit-overflow-scrolling'] = 'touch'; - } - if(scrollbars == 'verticalAsNeeded') { - stateCss['overflow-x'] = 'hidden'; - stateCss['-ms-overflow-x'] = 'hidden'; - } else if(scrollbars == 'horizontalAsNeeded') { - stateCss['overflow-y'] = 'hidden'; - stateCss['-ms-overflow-y'] = 'hidden'; - } - panel.css(panelCss); - panel.children().css(stateCss); - } - }; - - var _getShownStateId = function (id) { - var obj = $obj(id); - if (!obj || !$ax.public.fn.IsDynamicPanel(obj.type)) return id; - - var children = $ax.visibility.applyWidgetContainer(id, true, false, true).children(); - for (var i = 0; i < children.length; i++) { - var child = children[i]; - while ($ax.visibility.isContainer(child.id)) child = $(child).children()[0]; - if (child && child.style && child.style.display != 'none') return child.id; - } - return id; - }; - - var _getShownStateObj = function(id) { return $ax('#' + _getShownStateId(id));} - - _dynamicPanelManager.getShownState = function (id) { return $jobj(_getShownStateId(id)); }; - - var _getClamp = function(id) { - var obj = $obj(id); - if(!obj) return $ax('#' + id); - if ($ax.public.fn.IsDynamicPanel(obj.type)) return _getShownStateObj(id); - return $ax('#' + id); - }; - - var _updateFitPanel = function(panelId, stateIndex) { - if(!panelId) return false; - - // Only fit if fitToContent is true - if(!$ax.dynamicPanelManager.isIdFitToContent(panelId)) return false; - - // Traverse through children to find what size it should be. - var stateId = $ax.repeater.applySuffixToElementId(panelId, '_state' + stateIndex); - - var stateContentId = stateId + '_content'; - var stateQuery = $jobj(stateId); - - //var size = getContainerSize(stateContentId); - var childrenRect = $ax('#' + stateContentId).childrenBoundingRect(); - var size = {width: childrenRect.right, height: childrenRect.bottom}; - - // Skip if size hasn't changed - var oldWidth = stateQuery.width(); - var oldHeight = stateQuery.height(); - if(oldWidth == size.width && oldHeight == size.height) return false; - - var isPercentWidth = $obj(panelId).percentWidth; - if(!isPercentWidth) stateQuery.width(size.width); - stateQuery.height(size.height); - - //updatePercentWidth on all child panels - $jobj(stateContentId).children('.ax_dynamic_panel').each( - function() { _updatePanelPercentWidth(this.id); } - ); - - //do the following only if it is the current state - if(stateId != $ax.visibility.GetPanelState(panelId)) return false; - - //var panelQuery = $jobj(panelId); - //if (!isPercentWidth) panelQuery.attr('data-width', size.width); - //panelQuery.attr('data-height', size.height); - $ax.visibility.setResizedSize(panelId, isPercentWidth ? $ax('#' + panelId).width() : size.width, size.height); - - _adjustFixed(panelId, oldWidth, oldHeight, size.width, size.height); - - $ax.event.raiseSyntheticEvent(panelId, 'onResize'); - $ax.flyoutManager.updateFlyout(panelId); - - return true; - }; - - // widgetId is the one that crawls up masters until it finds a parent panel, targetId is the original widgetId (not the crawling master) - // finds the immediate parent panel and crawls up through masters but not repeaters - var getParentPanel = function(widgetId, path, targetId) { - path = path || $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(widgetId)); - - var obj = $obj(widgetId); - if(obj.parentDynamicPanel) { - path[path.length - 1] = obj.parentDynamicPanel; - var parentId = $ax.getScriptIdFromPath(path); - if(!parentId) return undefined; - parentId = $ax.repeater.getElementId(parentId, widgetId); - var parentObj = $obj(parentId); - var retVal = { parent: parentId }; - for(var i = 0; i < parentObj.diagrams.length; i++) { - var stateId = $ax.repeater.applySuffixToElementId(parentId, '_state' + i); - var stateQuery = $jobj(stateId); - if(stateQuery.find('#' + (targetId || widgetId)).length != 0) { - retVal.state = i; - retVal.stateId = stateId; - break; - } - } - return retVal; - } - - if(path.length == 1) return undefined; - - path.pop(); - var parentMaster = $ax.getScriptIdFromPath(path); - if(!parentMaster) return undefined; - parentMaster = $ax.repeater.getElementId(parentMaster, widgetId); - - //check if the master is in the same repeater as the widgetId widget - var parentMasterItemId = $ax.repeater.getItemIdFromElementId(parentMaster); - var widgetItemId = $ax.repeater.getItemIdFromElementId(widgetId); - if(parentMasterItemId != widgetItemId) return undefined; - - return getParentPanel(parentMaster, path, targetId || widgetId); - }; - - // finds the immediate parent layer and crawls up through masters but not repeaters or panels - var getParentLayer = function (widgetId, path) { - path = path || $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(widgetId)); - - //gets immediate parent layer only - var layerId = $ax.getLayerParentFromElementId(widgetId); - if(layerId) return layerId; - - if(path.length == 1) return undefined; - - path.pop(); - var parentMaster = $ax.getScriptIdFromPath(path); - if(!parentMaster) return undefined; - parentMaster = $ax.repeater.getElementId(parentMaster, widgetId); - - //check if the master is in the same panel as the widgetId widget - var widgetParentPanel = getParentPanel(widgetId); - if(widgetParentPanel) { - var parentMasterParentPanel = getParentPanel(parentMaster); - if(!parentMasterParentPanel || widgetParentPanel.parent != parentMasterParentPanel.parent) return undefined; - } - - //check if the master is in the same repeater as the widgetId widget - var parentMasterItemId = $ax.repeater.getItemIdFromElementId(parentMaster); - var widgetItemId = $ax.repeater.getItemIdFromElementId(widgetId); - if(parentMasterItemId != widgetItemId) return undefined; - - return getParentLayer(parentMaster, path); - }; - - //// TODO: May be a better location for this. Used currently for rdo and panel state containers - //var getContainerSize = function(containerId) { - // var containerQuery = containerId ? $jobj(containerId) : $('#base'); - // var children = containerQuery.children(); - // // Default size - // var size = { width: 0, height: 0 }; - // for(var i = 0; i < children.length; i++) { - // var child = $(children[i]); - // var childId = child.attr('id'); - // //var axChild = $ax('#' + childId).width(); - - // var childObj = $obj(childId); - // if(!childObj) { - // // On the body there are some children that should be ignored, as they are not objects. - // if(!child.hasClass('basiclink') || child.get(0).tagName.toLowerCase() != 'a') continue; - - // // Otherwise it should be a basic link - // var linkChildren = child.children(); - // if(!linkChildren.length) continue; - // child = $(linkChildren[0]); - // childId = child.attr('id'); - // childObj = $obj(childId); - // } - - // // Ignore fixed - // if(!childId || $ax.visibility.limboIds[childId] || !$ax.visibility.IsIdVisible(childId) - // || $ax.public.fn.IsDynamicPanel(childObj.type) && childObj.fixedHorizontal) continue; - - // var boundingRect = $ax.public.fn.getWidgetBoundingRect(childId); - // var position = { left: boundingRect.left, top: boundingRect.top }; - // var width = boundingRect.width; - // var height = boundingRect.height; - - // if($ax.public.fn.IsMaster(childObj.type)) { - // var masterSize = getContainerSize(childId); - // width = masterSize.width; - // height = masterSize.height; - // // } else if($ax.public.fn.IsRepeater(childObj.type)) { - // // var repeaterSize = $ax.repeater.getRepeaterSize(childId); - // // width = repeaterSize.width; - // // height = repeaterSize.height; - - // // if(width == 0 && height == 0) continue; - - // // position.left += childObj.x; - // // position.top += childObj.y; - // } else if ($ax.public.fn.IsDynamicPanel(childObj.type)) { - // if($ax.dynamicPanelManager.isIdFitToContent(childId)) { - // var stateQuery = $jobj($ax.visibility.GetPanelState(childId)); - // width = stateQuery.width(); - // height = stateQuery.height(); - // } - // } - - // size.width = Math.max(size.width, position.left + width); - // size.height = Math.max(size.height, position.top + height); - // } - - // return size; - //}; - //_dynamicPanelManager.getContainerSize = getContainerSize; - - var _adjustFixed = _dynamicPanelManager.adjustFixed = function(panelId, oldWidth, oldHeight, width, height) { - var loc = _getFixedPosition(panelId, oldWidth, oldHeight, width, height); - if(loc) { - $ax.action.addAnimation(panelId, $ax.action.queueTypes.move, function() { - $ax.move.MoveWidget(panelId, loc[0], loc[1], { easing: 'none', duration: 0 }, false, null, true); - }); - } - }; - - var _getFixedPosition = _dynamicPanelManager.getFixedPosition = function(panelId, oldWidth, oldHeight, width, height) { - var panelObj = $obj(panelId); - var x = 0; - var y = 0; - if(panelObj.fixedHorizontal == 'center') { - x = (oldWidth - width) / 2; - } - if(panelObj.fixedVertical == 'middle') { - y = (oldHeight - height) / 2; - } - return x == 0 && y == 0 ? undefined : [x, y]; - }; - - _dynamicPanelManager.getFixedInfo = function(panelId) { - var panelObj = $obj(panelId); - if (!panelObj || !$ax.public.fn.IsDynamicPanel(panelObj.type)) return {}; - var jobj = $jobj(panelId); - if(jobj.css('position') == 'absolute') return {}; - - var info = {}; - var horizontal = panelObj.fixedHorizontal; - if(!horizontal) return info; - - info.fixed = true; - info.horizontal = horizontal; - info.vertical = panelObj.fixedVertical; - - if (info.horizontal == 'left') info.x = $ax.getNumFromPx(jobj.css('left')); - else if (info.horizontal == 'center') info.x = $ax.getNumFromPx(jobj.css('margin-left')); - else if (info.horizontal == 'right') info.x = $ax.getNumFromPx(jobj.css('right')); - - if (info.vertical == 'top') info.y = $ax.getNumFromPx(jobj.css('top')); - else if (info.vertical == 'middle') info.y = $ax.getNumFromPx(jobj.css('margin-top')); - else if (info.vertical == 'bottom') info.y = $ax.getNumFromPx(jobj.css('bottom')); - - return info; - }; - - // Show isn't necessary if this is always done before toggling (which is currently true), but I don't want that - // change (if it happened) to break this. - var _compressToggle = function (id, vert, show, easing, duration) { - var layer = $ax.getTypeFromElementId(id) == $ax.constants.LAYER_TYPE; - var locProp = vert ? 'top' : 'left'; - var dimProp = vert ? 'height' : 'width'; - - var threshold; - var delta; - - threshold = $ax('#' + id)[locProp](true); - delta = layer ? $ax('#' + id)[dimProp]() : _getShownStateObj(id)[dimProp](); - - if(!show) { - // Need to make threshold bottom/right - threshold += delta; - // Delta is in the opposite direction - delta *= -1; - } - - _compress(id, vert, threshold, delta, easing, duration); - }; - _dynamicPanelManager.compressToggle = _compressToggle; - - // Used when setting state of dynamic panel - var _compressDelta = function(id, oldState, newState, vert, easing, duration) { - var oldQuery = $jobj(oldState); - var newQuery = $jobj(newState); - - var thresholdProp = vert ? 'top' : 'left'; - var thresholdOffset = vert ? 'height' : 'width'; - var threshold = $ax('#' + id)[thresholdProp](true); - threshold += oldQuery[thresholdOffset](); - - var delta = newQuery[thresholdOffset]() - oldQuery[thresholdOffset](); - - var clampOffset = vert ? 'width' : 'height'; - var clampWidth = Math.max(oldQuery[clampOffset](), newQuery[clampOffset]()); - - _compress(id, vert, threshold, delta, easing, duration, clampWidth); - }; - _dynamicPanelManager.compressDelta = _compressDelta; - - var _compress = function (id, vert, threshold, delta, easing, duration, clampWidth) { - // If below, a horizantal clamp, otherwise a vertical clamp - var clamp = { - prop: vert ? 'left' : 'top', - offset: vert ? 'width' : 'height' - }; - - // Get clamp in coords relative to parent. Account for layers farther down - if($ax.getTypeFromElementId(id) == $ax.constants.LAYER_TYPE) { - clamp.start = $ax('#' + id)[clamp.prop](true); - clamp.end = clamp.start + $ax('#' + id)[clamp.offset](); - } else { - var clampLoc = $jobj(id); - if(typeof clampWidth == 'undefined') clampWidth = _getClamp(id)[clamp.offset](); - - clamp.start = $ax.getNumFromPx(clampLoc.css(clamp.prop)); - clamp.end = clamp.start + clampWidth; - } - - // If clamps, threshold, or delta is not a number, can't compress. - if (isNaN(clamp.start) || isNaN(clamp.end) || isNaN(threshold) || isNaN(delta)) return; - - // Update clamp if fixed, to account for body position (only necessary when page centered) - if($jobj(id).css('position') == 'fixed') { - var clampDelta = $('#base').position().left; - clamp.start -= clampDelta; - clamp.end -= clampDelta; - } - - if(!easing) { - easing = 'none'; - duration = 0; - } - var parent = $ax('#' + id).getParents(false, ['item', 'state', 'layer'])[0]; - var obj = parent && $ax.getObjectFromElementId($ax.repeater.removeSuffixFromElementId(parent)); - // Go until you hit a parent item or state, or a layer that is hidden to use as parent. - // Account for layer container positions as you go. - while(obj && $ax.public.fn.IsLayer(obj.type) && $ax.visibility.IsIdVisible(parent)) { - var container = $ax.visibility.applyWidgetContainer(parent, true, true); - // If layer is using container, offset is going to be necessary - if(container.length) { - var offsetX = $ax.getNumFromPx(container.css('left')); - var offsetY = $ax.getNumFromPx(container.css('top')); - var clampProp = clamp.prop == 'left' ? offsetX : offsetY; - var threshProp = clamp.prop == 'left' ? offsetY : offsetX; - threshold += threshProp; - clamp.start += clampProp; - clamp.end += clampProp; - } - - parent = $ax('#' + parent).getParents(false, ['item', 'state', 'layer'])[0]; - obj = parent && $ax.getObjectFromElementId($ax.repeater.removeSuffixFromElementId(parent)); - } - - // Add container mid push causes strange behavior because we take container into account as we go down, but if after we accounted for it, - // a container is added, that container is not accounted for with threshold and clamp values. - var layer = obj && $ax.public.fn.IsLayer(obj.type) && parent; - if(layer) { - // If your parent layer is invisible, you want to be relative to it's container. That is true already if it has a container, - // but if you are just adding one now, then you need to offset your values - var needsOffset = !$jobj(layer + '_container').length && !$ax.visibility.IsIdVisible(layer); - $ax.visibility.pushContainer(layer, false); - if(needsOffset) { - container = $jobj(layer + '_container'); - offsetX = $ax.getNumFromPx(container.css('left')); - offsetY = $ax.getNumFromPx(container.css('top')); - clampProp = clamp.prop == 'left' ? offsetX : offsetY; - threshProp = clamp.prop == 'left' ? offsetY : offsetX; - threshold -= threshProp; - clamp.start -= clampProp; - clamp.end -= clampProp; - } - } - - var scrollParentObj = parent ? $('#' + parent) : undefined; - var parentScrollLeft = parent ? scrollParentObj.scrollLeft() : 0; - var parentScrollTop = parent ? scrollParentObj.scrollTop() : 0; - - // Note: If parent is body, some of these aren't widgets - if(parent && $jobj(parent + '_content').length > 0) parent = parent + '_content'; - if(parent && $jobj(parent + '_container').length > 0) parent = parent + '_container'; - - var windowObj = $(window); - var scrollLeft = windowObj.scrollLeft(); - var scrollTop = windowObj.scrollTop(); - var parentObj = $(parent ? '#' + parent : '#base'); - // hide parent to prevent layout thrashing - parentObj.hide(); - - _compressChildrenHelper(id, parentObj.children(), vert, threshold, delta, clamp, easing, duration); - - parentObj.show(); - // restore scroll if hide/show parent caused it to change - if(0 != parentScrollLeft) scrollParentObj.scrollLeft(parentScrollLeft); - if(0 != parentScrollTop) scrollParentObj.scrollTop(parentScrollTop); - if(windowObj.scrollLeft() != scrollLeft) windowObj.scrollLeft(scrollLeft); - if(windowObj.scrollTop() != scrollTop) windowObj.scrollTop(scrollTop); - - if(layer) $ax.visibility.popContainer(layer, false); - - // Do item push - var itemId = $ax.repeater.getItemIdFromElementId(id); - if(!itemId) return; - - var repeaterId = $ax.getParentRepeaterFromElementId(id); - // Only need to push when parent is an item directly. - if(parent != $ax.repeater.createElementId(repeaterId, itemId)) return; - - // If repeater is fit to content, then don't worry about it, it'll be handled elsewhere - if(!obj.repeaterPropMap.fitToContent) $ax.repeater.pushItems(repeaterId, itemId, delta, vert); - }; - - var _layerMayNeedCompress = function (layerId, vert, threshold, clamp, parentLayer) { - var boundingRect = $ax('#' + layerId).offsetBoundingRect(); - var marker, layerClamp; - - marker = (vert ? boundingRect.top : boundingRect.left) + (vert ? boundingRect.height : boundingRect.width); - layerClamp = clamp.prop == 'left' ? [boundingRect.left] : [boundingRect.top]; - layerClamp[1] = layerClamp[0] + (clamp.offset == 'width' ? boundingRect.width : boundingRect.height); - - if (parentLayer) { - var axParent = $ax('#' + parentLayer); - marker -= Number(axParent[vert ? 'top' : 'left'](true)); - layerClamp[0] -= Number(axParent[clamp.prop](true)); - } - - if (isNaN(marker) || isNaN(layerClamp[0]) || isNaN(layerClamp[1]) || - marker < threshold || layerClamp[1] <= clamp.start || layerClamp[0] >= clamp.end) { - return false; - } - return true; - } - - var _compressChildrenHelper = function (id, children, vert, threshold, delta, clamp, easing, duration, parentLayer) { - var toMove = []; - var allMove = true; - for (var i = 0; i < children.length; i++) { - var child = $(children[i]); - - // Check for basic links - if(child[0] && child[0].tagName == 'A' && child.hasClass('basiclink')) child = child.children(); - var childId = child.attr('id'); - - // TODO: Played with this a lot, went with a safer fix, but I don't like the catch all with !$obj(childId), should handle these cases explicitally. - // ann/ref suffixes should skip without turning off allMove, lightbox should be skipped, and is unclear if allMove should be turned off, I think others including container, inner_container, div, img, and text should not be hit ever. - // Don't move self, and check id to make sure it a widget and not a fixed panel - if(childId == id || !childId || childId[0] != 'u' || !$obj(childId) || $obj(childId).fixedVertical) { - // ann/ref widgets should not stop allMove, they move if their widget does, and that widget will be checked and turn this off if it doesn't move - var suffix = childId && childId.split('_')[1]; - allMove = allMove && (suffix == 'ann' || suffix == 'ref'); - continue; - } - - if ($ax.getTypeFromElementId(childId) == $ax.constants.LAYER_TYPE) { - // containerizing children can cause layout thrashing, if no children will possibly need to be moved based on layer position/size then don't do it - if (!_layerMayNeedCompress(childId, vert, threshold, clamp, parentLayer)) { - allMove = false; - continue; - } - - $ax.visibility.pushContainer(childId, false); - var addSelf; - var container = $ax.visibility.applyWidgetContainer(childId, true, true); - var layerChildren = (container.length ? container : child).children(); - //if(container.length) { - var offsetX = -$ax.getNumFromPx(container.css('left')); - var offsetY = -$ax.getNumFromPx(container.css('top')); - var clampProp = clamp.prop == 'left' ? offsetX : offsetY; - var threshProp = clamp.prop == 'left' ? offsetY : offsetX; - var layerClamp = { prop: clamp.prop, offset: clamp.offset, start: clamp.start + clampProp, end: clamp.end + clampProp }; - addSelf = _compressChildrenHelper(id, layerChildren, vert, threshold + threshProp, delta, layerClamp, easing, duration, childId); - //} else addSelf = _compressChildrenHelper(id, layerChildren, vert, threshold, delta, clamp, easing, duration, childId); - - if(addSelf) toMove.push(childId); - else allMove = false; - $ax.visibility.popContainer(childId, false); - continue; - } - - var numbers = childId.substring(1).split('-'); - if(numbers.length < 1 || isNaN(Number(numbers[0])) || (numbers.length == 2 && isNaN(Number(numbers[1]))) || numbers.length > 2) continue; - - var marker, childClamp; - - var axChild = $ax('#' + childId); - var markerProp = vert ? 'top' : 'left'; - marker = Number(axChild[markerProp](true)); - childClamp = [Number(axChild[clamp.prop](true))]; - - if(parentLayer) { - var axParent = $ax('#' + parentLayer); - marker -= Number(axParent[markerProp](true)); - childClamp[0] -= Number(axParent[clamp.prop](true)); - } - - // Dynamic panels are not reporting correct size sometimes, so pull it from the state. Get shown state just returns the widget if it is not a dynamic panel. - var sizeChild = _getShownStateObj(childId); - childClamp[1] = childClamp[0] + sizeChild[clamp.offset](); - - if(isNaN(marker) || isNaN(childClamp[0]) || isNaN(childClamp[1]) || - marker < threshold || childClamp[1] <= clamp.start || childClamp[0] >= clamp.end) { - allMove = false; - continue; - } - - toMove.push(childId); - } - - if (allMove && parentLayer) { - return true; - } else { - for(var i = 0; i < toMove.length; i++) { - $ax('#' + toMove[i]).moveBy(vert ? 0 : delta, vert ? delta : 0, easing == 'none' ? {} : { duration: duration, easing: easing }); - } - } - return false; - }; - - var _parentHandlesStyles = function(id) { - var parents = $ax('#' + id).getParents(true, ['dynamicPanel', 'layer'])[0]; - if(!parents) return false; - var directParent = true; - for(var i = 0; i < parents.length; i++) { - var parentId = parents[i]; - var parentObj = $obj(parentId); - if(!parentObj.propagate) { - directParent = false; - continue; - } - return { id: parentId, direct: directParent }; - } - return false; - }; - _dynamicPanelManager.parentHandlesStyles = _parentHandlesStyles; - - var _propagateMouseOver = function(id, value) { - propagate(id, true, value); - }; - _dynamicPanelManager.propagateMouseOver = _propagateMouseOver; - - var _propagateMouseDown = function(id, value) { - propagate(id, false, value); - }; - _dynamicPanelManager.propagateMouseDown = _propagateMouseDown; - - var propagate = function(id, hover, value) { - var hoverChildren = function(children) { - if(!children) return; - for(var i = 0; i < children.length; i++) { - var elementId = children[i].id; - var obj = $obj(elementId); - if(obj == null) { - elementId = elementId.split('_')[0]; - obj = $obj(elementId); - } - if(obj == null) continue; - if (($ax.public.fn.IsDynamicPanel(obj.type) || $ax.public.fn.IsLayer(obj.type)) && !obj.propagate) continue; - - if(hover) $ax.style.SetWidgetHover(elementId, value); - else $ax.style.SetWidgetMouseDown(elementId, value); - $ax.annotation.updateLinkLocations(elementId); - - hoverChildren(children[i].children); - } - }; - hoverChildren($ax('#' + id).getChildren(true)[0].children); - }; -}); diff --git a/web/main/static/resources/scripts/axure/sto.js b/web/main/static/resources/scripts/axure/sto.js deleted file mode 100644 index 8cf67aa..0000000 --- a/web/main/static/resources/scripts/axure/sto.js +++ /dev/null @@ -1,241 +0,0 @@ - -$axure.internal(function($ax) { - var funcs = {}; - - var weekday = new Array(7); - weekday[0] = "Sunday"; - weekday[1] = "Monday"; - weekday[2] = "Tuesday"; - weekday[3] = "Wednesday"; - weekday[4] = "Thursday"; - weekday[5] = "Friday"; - weekday[6] = "Saturday"; - - funcs.getDayOfWeek = function() { - return _getDayOfWeek(this.getDay()); - }; - - var _getDayOfWeek = $ax.getDayOfWeek = function(day) { - return weekday[day]; - }; - - var month = new Array(12); - month[0] = "January"; - month[1] = "February"; - month[2] = "March"; - month[3] = "April"; - month[4] = "May"; - month[5] = "June"; - month[6] = "July"; - month[7] = "August"; - month[8] = "September"; - month[9] = "October"; - month[10] = "November"; - month[11] = "December"; - - funcs.getMonthName = function() { - return _getMonthName(this.getMonth()); - }; - - var _getMonthName = $ax.getMonthName = function(monthNum) { - return month[monthNum]; - }; - - funcs.getMonth = function() { - return this.getMonth() + 1; - }; - - funcs.addYears = function(years) { - var retVal = new Date(this.valueOf()); - retVal.setFullYear(this.getFullYear() + Number(years)); - return retVal; - }; - - funcs.addMonths = function(months) { - var retVal = new Date(this.valueOf()); - retVal.setMonth(this.getMonth() + Number(months)); - return retVal; - }; - - funcs.addDays = function(days) { - var retVal = new Date(this.valueOf()); - retVal.setDate(this.getDate() + Number(days)); - return retVal; - }; - - funcs.addHours = function(hours) { - var retVal = new Date(this.valueOf()); - retVal.setHours(this.getHours() + Number(hours)); - return retVal; - }; - - funcs.addMinutes = function(minutes) { - var retVal = new Date(this.valueOf()); - retVal.setMinutes(this.getMinutes() + Number(minutes)); - return retVal; - }; - - funcs.addSeconds = function(seconds) { - var retVal = new Date(this.valueOf()); - retVal.setSeconds(this.getSeconds() + Number(seconds)); - return retVal; - }; - - funcs.addMilliseconds = function(milliseconds) { - var retVal = new Date(this.valueOf()); - retVal.setMilliseconds(this.getMilliseconds() + Number(milliseconds)); - return retVal; - }; - - var _stoHandlers = {}; - - _stoHandlers.literal = function(sto, scope, eventInfo) { - return sto.value; - }; - - //need angle bracket syntax because var is a reserved word - _stoHandlers['var'] = function(sto, scope, eventInfo) { - // Can't us 'A || B' here, because the first value can be false, true, or empty string and still be valid. - var retVal = scope.hasOwnProperty(sto.name) ? scope[sto.name] : $ax.globalVariableProvider.getVariableValue(sto.name, eventInfo); - // Handle desired type here? - - if(retVal && retVal.exprType) { - retVal = $ax.expr.evaluateExpr(retVal, eventInfo); - } - - if((sto.desiredType == 'int' || sto.desiredType == 'float')) { - var num = new Number(retVal); - retVal = isNaN(num.valueOf()) ? retVal : num; - } - - - return retVal; - }; - - //TODO: Perhaps repeaterId can be detirmined at generation, and stored in the sto info. - _stoHandlers.item = function(sto, scope, eventInfo, prop) { - prop = prop || (eventInfo.data ? 'data' : eventInfo.link ? 'url' : eventInfo.image ? 'img' : 'text'); - var id = sto.isTarget || !$ax.repeater.hasData(eventInfo.srcElement, sto.name) ? eventInfo.targetElement : eventInfo.srcElement; - return getData(eventInfo, id, sto.name, prop); - }; - - var getData = function(eventInfo, id, name, prop) { - var repeaterId = $ax.getParentRepeaterFromScriptId($ax.repeater.getScriptIdFromElementId(id)); - var itemId = $ax.repeater.getItemIdFromElementId(id); - return $ax.repeater.getData(eventInfo, repeaterId, itemId, name, prop); - }; - - _stoHandlers.paren = function(sto, scope, eventInfo) { - return _evaluateSTO(sto.innerSTO, scope, eventInfo); - }; - - _stoHandlers.fCall = function(sto, scope, eventInfo) { - //TODO: [mas] handle required type - var thisObj = _evaluateSTO(sto.thisSTO, scope, eventInfo); - if(sto.thisSTO.desiredType == 'string' && sto.thisSTO.computedType != 'string') thisObj = thisObj.toString(); - - var args = []; - for(var i = 0; i < sto.arguments.length; i++) { - args[i] = _evaluateSTO(sto.arguments[i], scope, eventInfo); - } - var fn = (funcs.hasOwnProperty(sto.func) && funcs[sto.func]) || thisObj[sto.func]; - return fn.apply(thisObj, args); - }; - - _stoHandlers.propCall = function(sto, scope, eventInfo) { - //TODO: [mas] handle required type - if((sto.prop == 'url' || sto.prop == 'img') && sto.thisSTO.sto == 'item') return _stoHandlers.item(sto.thisSTO, scope, eventInfo, sto.prop); - var thisObj = _evaluateSTO(sto.thisSTO, scope, eventInfo); - - // calculate cursor offset for elements that are located relative to their parents - if (sto.thisSTO.name == 'cursor') { - var cursorOffset = $ax.public.fn.getCursorOffset(eventInfo.targetElement); - thisObj = { - x: thisObj.x - cursorOffset.x, - y: thisObj.y - cursorOffset.y, - }; - } - - var prop = thisObj[sto.prop] instanceof Function ? thisObj[sto.prop]() : thisObj[sto.prop]; - return prop; - }; - - var _binOps = {}; - _binOps['+'] = function(left, right) { - if(left instanceof Date) return addDayToDate(left, right); - if(right instanceof Date) return addDayToDate(right, left); - - var num = Number(left) + Number(right); - return isNaN(num) ? (String(left) + String(right)) : num; - }; - _binOps['-'] = function(left, right) { - if(left instanceof Date) return addDayToDate(left, -right); - return left - right; - }; - _binOps['*'] = function(left, right) { return Number(left) * Number(right); }; - _binOps['/'] = function(left, right) { return Number(left) / Number(right); }; - _binOps['%'] = function(left, right) { return Number(left) % Number(right); }; - _binOps['=='] = function(left, right) { return _getBool(left) == _getBool(right); }; - _binOps['!='] = function(left, right) { return _getBool(left) != _getBool(right); }; - _binOps['<'] = function(left, right) { return Number(left) < Number(right); }; - _binOps['<='] = function(left, right) { return Number(left) <= Number(right); }; - _binOps['>'] = function(left, right) { return Number(left) > Number(right); }; - _binOps['>='] = function(left, right) { return Number(left) >= Number(right); }; - _binOps['&&'] = function(left, right) { return _getBool(left) && _getBool(right); }; - _binOps['||'] = function(left, right) { return _getBool(left) || _getBool(right); }; - - // TODO: Move this to generic place to be used. - var addDayToDate = function(date, days) { - var retVal = new Date(date.valueOf()); - retVal.setDate(date.getDate() + days); - return retVal; - }; - - var _unOps = {}; - _unOps['+'] = function(arg) { return +arg; }; - _unOps['-'] = function(arg) { return -arg; }; - _unOps['!'] = function(arg) { return !_getBool(arg); }; - - _stoHandlers.binOp = function(sto, scope, eventInfo) { - var left = _evaluateSTO(sto.leftSTO, scope, eventInfo); - var right = _evaluateSTO(sto.rightSTO, scope, eventInfo); - return _binOps[sto.op](left, right); - }; - - _stoHandlers.unOp = function(sto, scope, eventInfo) { - var input = _evaluateSTO(sto.inputSTO, scope, eventInfo); - return _unOps[sto.op](input); - }; - - var _getBool = function(val) { - var lowerVal = val.toLowerCase ? val.toLowerCase() : val; - return lowerVal == "false" ? false : lowerVal == "true" ? true : val; - }; - $ax.getBool = _getBool; - - var _evaluateSTO = function(sto, scope, eventInfo) { - if(sto.sto == 'error') return undefined; - return _tryEscapeRichText(castSto(_stoHandlers[sto.sto](sto, scope, eventInfo), sto), eventInfo); - }; - $ax.evaluateSTO = _evaluateSTO; - - var castSto = function(val, sto) { - var type = sto.computedType || sto.desiredType; - if(type == 'string') val = String(val); - else if(type == 'date' && !(val instanceof Date)) val = new Date(val); - else if(type == 'int' || type == 'float') val = Number(val); - else if(type == 'bool') val = Boolean(val); - - return val; - }; - - var _tryEscapeRichText = function(text, eventInfo) { - return eventInfo.htmlLiteral ? _escapeRichText(text) : text; - }; - - var _escapeRichText = function(text) { - if(typeof (text) != 'string') return text; - - return text.replace('<', '<'); - }; -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/style.js b/web/main/static/resources/scripts/axure/style.js deleted file mode 100644 index 0d7399a..0000000 --- a/web/main/static/resources/scripts/axure/style.js +++ /dev/null @@ -1,1389 +0,0 @@ -$axure.internal(function($ax) { - var _style = {}; - $ax.style = _style; - - var _disabledWidgets = {}; - var _selectedWidgets = {}; - - // A table to cache the outerHTML of the _rtf elements before the rollover state is applied. - var _originalTextCache = {}; - // A table to exclude the normal style from adaptive overrides - var _shapesWithSetRichText = {}; - - // just a listing of shape ids - var _adaptiveStyledWidgets = {}; - - var _setLinkStyle = function(id, styleName) { - var parentId = $ax.GetParentIdFromLink(id); - var style = _computeAllOverrides(id, parentId, styleName, $ax.adaptive.currentViewId); - - var textId = $ax.GetTextPanelId(parentId); - if(!_originalTextCache[textId]) { - $ax.style.CacheOriginalText(textId); - } - if($.isEmptyObject(style)) return; - - var textCache = _originalTextCache[textId].styleCache; - - _transformTextWithVerticalAlignment(textId, function() { - var cssProps = _getCssStyleProperties(style); - $('#' + id).find('*').addBack().each(function(index, element) { - element.setAttribute('style', textCache[element.id]); - _applyCssProps(element, cssProps); - }); - }); - }; - - var _resetLinkStyle = function(id) { - var textId = $ax.GetTextPanelId($ax.GetParentIdFromLink(id)); - var textCache = _originalTextCache[textId].styleCache; - - _transformTextWithVerticalAlignment(textId, function() { - $('#' + id).find('*').addBack().each(function(index, element) { - element.style.cssText = textCache[element.id]; - }); - }); - if($ax.event.mouseDownObjectId) { - $ax.style.SetWidgetMouseDown($ax.event.mouseDownObjectId, true); - } else if($ax.event.mouseOverObjectId) { - $ax.style.SetWidgetHover($ax.event.mouseOverObjectId, true); - } - }; - - $ax.style.SetLinkHover = function(id) { - _setLinkStyle(id, MOUSE_OVER); - }; - - $ax.style.SetLinkNotHover = function(id) { - _resetLinkStyle(id); - }; - - $ax.style.SetLinkMouseDown = function(id) { - _setLinkStyle(id, MOUSE_DOWN); - }; - - $ax.style.SetLinkNotMouseDown = function(id) { - _resetLinkStyle(id); - var style = _computeAllOverrides(id, $ax.event.mouseOverObjectId, MOUSE_OVER, $ax.adaptive.currentViewId); - - if(!$.isEmptyObject(style)) $ax.style.SetLinkHover(id); - //we dont do anything here because the widget not mouse down has taken over here - }; - - var _widgetHasState = function(id, state) { - if($ax.style.getElementImageOverride(id, state)) return true; - var diagramObject = $ax.getObjectFromElementId(id); - - //var adaptiveIdChain = $ax.adaptive.getAdaptiveIdChain($ax.adaptive.currentViewId); - var adaptiveIdChain = $ax.style.getViewIdChain($ax.adaptive.currentViewId, id, diagramObject); - - for(var i = 0; i < adaptiveIdChain.length; i++) { - var viewId = adaptiveIdChain[i]; - var adaptiveStyle = diagramObject.adaptiveStyles[viewId]; - if(adaptiveStyle && adaptiveStyle.stateStyles && adaptiveStyle.stateStyles[state]) return true; - } - - if(diagramObject.style.stateStyles) { - var stateStyle = diagramObject.style.stateStyles[state]; - if(!stateStyle) return false; - return !$.isEmptyObject(stateStyle); - } - - return false; - }; - - // Returns what overrides the hover, or false if nothing. - var _hoverOverride = function(id) { - if($ax.style.IsWidgetDisabled(id)) return DISABLED; - if($ax.style.IsWidgetSelected(id)) return SELECTED; - var obj = $ax.getObjectFromElementId(id); - if(!obj.isContained) return false; - var path = $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(id)); - path[path.length - 1] = obj.parent.id; - var itemId = $ax.repeater.getItemIdFromElementId(id); - return _hoverOverride($ax.getElementIdFromPath(path, { itemNum: itemId })); - }; - - $ax.style.SetWidgetHover = function(id, value) { - var override = _hoverOverride(id); - if(override == DISABLED) return; - if(!_widgetHasState(id, MOUSE_OVER)) return; - - var valToSet = value || _isRolloverOverride(id); - var state = _generateMouseState(id, valToSet ? MOUSE_OVER : NORMAL, override == SELECTED); - _applyImageAndTextJson(id, state); - _updateElementIdImageStyle(id, state); - }; - - var _rolloverOverrides = []; - var _isRolloverOverride = function(id) { - return _rolloverOverrides.indexOf(id) != -1; - }; - - $ax.style.AddRolloverOverride = function(id) { - if(_isRolloverOverride(id)) return; - _rolloverOverrides[_rolloverOverrides.length] = id; - if($ax.event.mouseOverIds.indexOf(id) == -1) $ax.style.SetWidgetHover(id, true); - }; - - $ax.style.RemoveRolloverOverride = function(id) { - var index = _rolloverOverrides.indexOf(id); - if(index == -1) return; - $ax.splice(_rolloverOverrides, index, 1); - if($ax.event.mouseOverIds.indexOf(id) == -1) $ax.style.SetWidgetHover(id, false); - }; - - // function GetWidgetCurrentState(id) { - // if($ax.style.IsWidgetDisabled(id)) return "disabled"; - // if($ax.style.IsWidgetSelected(id)) return "selected"; - // if($ax.event.mouseOverObjectId == id) return "mouseOver"; - // if($ax.event.mouseDownObjectId == id) return "mouseDown"; - - // return "normal"; - // } - - $ax.style.ObjHasMouseDown = function(id) { - var obj = $obj(id); - if($ax.style.getElementImageOverride(id, 'mouseDown') || obj.style && obj.style.stateStyles && obj.style.stateStyles.mouseDown) return true; - - //var chain = $ax.adaptive.getAdaptiveIdChain($ax.adaptive.currentViewId); - var chain = $ax.style.getViewIdChain($ax.adaptive.currentViewId, id, obj); - for(var i = 0; i < chain.length; i++) { - var style = obj.adaptiveStyles[chain[i]]; - if(style && style.stateStyles && style.stateStyles.mouseDown) return true; - } - return false; - }; - - $ax.style.SetWidgetMouseDown = function(id, value, checkMouseOver) { - if($ax.style.IsWidgetDisabled(id)) return; - if(!_widgetHasState(id, MOUSE_DOWN)) return; - - //if set to value is true, it's mousedown, if check mouseover is true, - //check if element is currently mouseover and has mouseover state before setting mouseover - if(value) var state = MOUSE_DOWN; - else if(!checkMouseOver || $ax.event.mouseOverIds.indexOf(id) !== -1 && _widgetHasState(id, MOUSE_OVER)) state = MOUSE_OVER; - else state = NORMAL; - - var mouseState = _generateMouseState(id, state, $ax.style.IsWidgetSelected(id)); - _applyImageAndTextJson(id, mouseState); - _updateElementIdImageStyle(id, mouseState); - }; - - var _generateMouseState = function(id, mouseState, selected) { - - var isSelectedFocused = function (state) { - if(!_widgetHasState(id, FOCUSED)) return state; - - var jObj = $('#' + id); - if(state == SELECTED) return (jObj.hasClass(FOCUSED)) ? SELECTED_FOCUSED : state; - else return (jObj.hasClass(FOCUSED) || jObj.hasClass(SELECTED_FOCUSED)) ? FOCUSED : state; - } - - if (selected) { - if (_style.getElementImageOverride(id, SELECTED)) return isSelectedFocused(SELECTED); - - var obj = $obj(id); - //var viewChain = $ax.adaptive.getAdaptiveIdChain($ax.adaptive.currentViewId); - var viewChain = $ax.style.getViewIdChain($ax.adaptive.currentViewId, id, obj); - viewChain[viewChain.length] = ''; - if($ax.IsDynamicPanel(obj.type) || $ax.IsLayer(obj.type)) return isSelectedFocused(SELECTED); - - var any = function(dict) { - for(var key in dict) return true; - return false; - }; - - for(var i = 0; i < viewChain.length; i++) { - var viewId = viewChain[i]; - // Need to check seperately for images. - var scriptId = $ax.repeater.getScriptIdFromElementId(id); - if(obj.adaptiveStyles && obj.adaptiveStyles[viewId] && any(obj.adaptiveStyles[viewId]) - || obj.images && (obj.images[scriptId + '~selected~' + viewId] || obj.images['selected~' + viewId])) return isSelectedFocused(SELECTED); - } - var selectedStyle = obj.style && obj.style.stateStyles && obj.style.stateStyles.selected; - if(selectedStyle && any(selectedStyle)) return isSelectedFocused(SELECTED); - } - - // Not using selected - return isSelectedFocused(mouseState); - }; - - $ax.style.SetWidgetFocused = function (id, value) { - if (_isWidgetDisabled(id)) return; - if (!_widgetHasState(id, FOCUSED)) return; - - if (value) var state = $ax.style.IsWidgetSelected(id) ? SELECTED_FOCUSED : FOCUSED; - else state = $ax.style.IsWidgetSelected(id) ? SELECTED : NORMAL; - - _applyImageAndTextJson(id, state); - _updateElementIdImageStyle(id, state); - } - - $ax.style.SetWidgetSelected = function(id, value, alwaysApply) { - if(_isWidgetDisabled(id)) return; - //NOTE: not firing select events if state didn't change - var raiseSelectedEvents = $ax.style.IsWidgetSelected(id) != value; - - if(value) { - var group = $('#' + id).attr('selectiongroup'); - if(group) { - $("[selectiongroup='" + group + "']").each(function() { - var otherId = this.id; - if(otherId == id) return; - if ($ax.visibility.isScriptIdLimbo($ax.repeater.getScriptIdFromElementId(otherId))) return; - $ax.style.SetWidgetSelected(otherId, false, alwaysApply); - }); - } - } - var obj = $obj(id); - if(obj) { - var actionId = id; - if ($ax.public.fn.IsDynamicPanel(obj.type) || $ax.public.fn.IsLayer(obj.type)) { - if(!value) $jobj(id).removeClass('selected'); - var children = $axure('#' + id).getChildren()[0].children; - var skipIds = new Set(); - for(var i = 0; i < children.length; i++) { - var childId = children[i]; - // only set one member of selection group in children selected since subsequent calls - // will unselect the previous one anyway - if(value) { - if(skipIds.has(childId)) continue; - var group = $('#' + childId).attr('selectiongroup'); - if(group) for (var item of $("[selectiongroup='" + group + "']")) skipIds.add(item.id); - } - // Special case for trees - var childObj = $jobj(childId); - if(childObj.hasClass('treeroot')) { - var treenodes = childObj.find('.treenode'); - for(var j = 0; j < treenodes.length; j++) { - $axure('#' + treenodes[j].id).selected(value); - } - } else $axure('#' + childId).selected(value); - } - } else { - var widgetHasSelectedState = _widgetHasState(id, SELECTED); - while(obj.isContained && !widgetHasSelectedState) obj = obj.parent; - var itemId = $ax.repeater.getItemIdFromElementId(id); - var path = $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(id)); - path[path.length - 1] = obj.id; - actionId = $ax.getElementIdFromPath(path, { itemNum: itemId }); - if(alwaysApply || widgetHasSelectedState) { - var state = _generateSelectedState(actionId, value); - _applyImageAndTextJson(actionId, state); - _updateElementIdImageStyle(actionId, state); - } - //added actionId and this hacky logic because we set style state on child, but interaction on parent - //then the id saved in _selectedWidgets would be depended on widgetHasSelectedState... more see case 1818143 - while(obj.isContained && !$ax.getObjectFromElementId(id).interactionMap) obj = obj.parent; - path = $ax.getPathFromScriptId($ax.repeater.getScriptIdFromElementId(id)); - path[path.length - 1] = obj.id; - actionId = $ax.getElementIdFromPath(path, { itemNum: itemId }); - } - } - - // ApplyImageAndTextJson(id, value ? 'selected' : 'normal'); - _selectedWidgets[id] = value; - if(raiseSelectedEvents) $ax.event.raiseSelectedEvents(actionId, value); - }; - - var _generateSelectedState = function(id, selected) { - var mouseState = $ax.event.mouseDownObjectId == id ? MOUSE_DOWN : $.inArray(id, $ax.event.mouseOverIds) != -1 ? MOUSE_OVER : NORMAL; - //var mouseState = $ax.event.mouseDownObjectId == id ? MOUSE_DOWN : $ax.event.mouseOverIds.indexOf(id) != -1 ? MOUSE_OVER : NORMAL; - return _generateMouseState(id, mouseState, selected); - }; - - $ax.style.IsWidgetSelected = function(id) { - return Boolean(_selectedWidgets[id]) || $('#'+id).hasClass('selected'); - }; - - $ax.style.SetWidgetEnabled = function(id, value) { - _disabledWidgets[id] = !value; - $('#' + id).find('a').css('cursor', value ? 'pointer' : 'default'); - - if(!_widgetHasState(id, DISABLED)) return; - if(!value) { - _applyImageAndTextJson(id, DISABLED); - _updateElementIdImageStyle(id, DISABLED); - } else $ax.style.SetWidgetSelected(id, $ax.style.IsWidgetSelected(id), true); - }; - - $ax.style.SetWidgetPlaceholder = function(id, active, text, password) { - var inputId = $ax.repeater.applySuffixToElementId(id, '_input'); - - // Right now this is the only style on the widget. If other styles (ex. Rollover), are allowed - // on TextBox/TextArea, or Placeholder is applied to more widgets, this may need to do more. - var obj = $jobj(inputId); - - var height = document.getElementById(inputId).style['height']; - var width = document.getElementById(inputId).style['width']; - obj.attr('style', ''); - //removing all styles, but now we can change the size, so we should add them back - //this is more like a quick hack - if (height) obj.css('height', height); - if (width) obj.css('width', width); - - if(!active) { - try { //ie8 and below error - if(password) document.getElementById(inputId).type = 'password'; - } catch(e) { } - } else { - var element = $('#' + inputId)[0]; - var style = _computeAllOverrides(id, undefined, HINT, $ax.adaptive.currentViewId); - var styleProperties = _getCssStyleProperties(style); - - //moved this out of GetCssStyleProperties for now because it was breaking un/rollovers with gradient fills - //if(style.fill) styleProperties.allProps.backgroundColor = _getColorFromFill(style.fill); - - _applyCssProps(element, styleProperties, true); - try { //ie8 and below error - if(password && text) document.getElementById(inputId).type = 'text'; - } catch(e) { } - } - obj.val(text); - }; - - var _isWidgetDisabled = $ax.style.IsWidgetDisabled = function(id) { - return Boolean(_disabledWidgets[id]); - }; - - var _elementIdsToImageOverrides = {}; - $ax.style.mapElementIdToImageOverrides = function (elementId, override) { - for(var key in override) _addImageOverride(elementId, key, override[key]); - }; - - var _addImageOverride = function (elementId, state, val) { - if (!_elementIdsToImageOverrides[elementId]) _elementIdsToImageOverrides[elementId] = {}; - _elementIdsToImageOverrides[elementId][state] = val; - } - - $ax.style.deleteElementIdToImageOverride = function(elementId) { - delete _elementIdsToImageOverrides[elementId]; - }; - - $ax.style.getElementImageOverride = function(elementId, state) { - var url = _elementIdsToImageOverrides[elementId] && _elementIdsToImageOverrides[elementId][state]; - return url; - }; - - $ax.style.elementHasAnyImageOverride = function(elementId) { - return Boolean(_elementIdsToImageOverrides[elementId]); - }; - - var NORMAL = 'normal'; - var MOUSE_OVER = 'mouseOver'; - var MOUSE_DOWN = 'mouseDown'; - var SELECTED = 'selected'; - var DISABLED = 'disabled'; - var HINT = 'hint'; - var FOCUSED = 'focused'; - var SELECTED_FOCUSED = 'selectedFocused'; - const SELECTED_DISABLED = 'selectedDisabled'; - $ax.constants.SELECTED_DISABLED = SELECTED_DISABLED; - var ALL_STATES = [MOUSE_OVER, MOUSE_DOWN, SELECTED, FOCUSED, SELECTED_FOCUSED, DISABLED]; - - var _generateState = _style.generateState = function(id) { - return $ax.placeholderManager.isActive(id) ? HINT : _style.IsWidgetDisabled(id) ? DISABLED : _generateSelectedState(id, _style.IsWidgetSelected(id)); - }; - - var _progressState = _style.progessState = function(state) { - if(state == NORMAL) return false; - if(state == MOUSE_DOWN) return MOUSE_OVER; - return NORMAL; - }; - - var _unprogressState = function(state, goal) { - state = state || NORMAL; - if(state == goal || state == SELECTED_FOCUSED) return undefined; - if(state == NORMAL && goal == MOUSE_DOWN) return MOUSE_OVER; - if(state == NORMAL && goal == SELECTED_FOCUSED) return SELECTED; - if(state == SELECTED && goal == SELECTED_FOCUSED) return FOCUSED; - return goal; - }; - - var _updateElementIdImageStyle = _style.updateElementIdImageStyle = function(elementId, state) { - if(!_style.elementHasAnyImageOverride(elementId)) return; - - if(!state) state = _generateState(elementId); - - var style = _computeFullStyle(elementId, state, $ax.adaptive.currentViewId); - - var query = $jobj($ax.repeater.applySuffixToElementId(elementId, '_img')); - style.size.width = query.width(); - style.size.height = query.height(); - var borderId = $ax.repeater.applySuffixToElementId(elementId, '_border'); - var borderQuery = $jobj(borderId); - if(!borderQuery.length) { - borderQuery = $('<div></div>'); - borderQuery.attr('id', borderId); - query.after(borderQuery); - } - - borderQuery.attr('style', ''); - //borderQuery.css('position', 'absolute'); - query.attr('style', ''); - - var borderQueryCss = { 'position': 'absolute' }; - var queryCss = {} - - var borderWidth = Number(style.borderWidth); - var hasBorderWidth = borderWidth > 0; - if(hasBorderWidth) { - //borderQuery.css('border-style', 'solid'); - //borderQuery.css('border-width', borderWidth + 'px'); // If images start being able to turn off borders on specific sides, need to update this. - //borderQuery.css('width', style.size.width - borderWidth * 2); - //borderQuery.css('height', style.size.height - borderWidth * 2); - //borderQuery.css({ - // 'border-style': 'solid', - // 'border-width': borderWidth + 'px', - // 'width': style.size.width - borderWidth * 2, - // 'height': style.size.height - borderWidth * 2 - //}); - borderQueryCss['border-style'] = 'solid'; - borderQueryCss['border-width'] = borderWidth + 'px'; // If images start being able to turn off borders on specific sides, need to update this. - borderQueryCss['width'] = style.size.width - borderWidth * 2; - borderQueryCss['height'] = style.size.height - borderWidth * 2; - } - - var linePattern = style.linePattern; - if(hasBorderWidth && linePattern) borderQueryCss['border-style'] = linePattern; - - var borderFill = style.borderFill; - if(hasBorderWidth && borderFill) { - var color = borderFill.fillType == 'solid' ? borderFill.color : - borderFill.fillType == 'linearGradient' ? borderFill.colors[0].color : 0; - - var alpha = Math.floor(color / 256 / 256 / 256); - color -= alpha * 256 * 256 * 256; - alpha = alpha / 255; - - var red = Math.floor(color / 256 / 256); - color -= red * 256 * 256; - var green = Math.floor(color / 256); - var blue = color - green * 256; - - borderQueryCss['border-color'] = _rgbaToFunc(red, green, blue, alpha); - } - - var cornerRadiusTopLeft = style.cornerRadius; - if(cornerRadiusTopLeft) { - queryCss['border-radius'] = cornerRadiusTopLeft + 'px'; - borderQueryCss['border-radius'] = cornerRadiusTopLeft + 'px'; - } - - var outerShadow = style.outerShadow; - if(outerShadow && outerShadow.on) { - var arg = ''; - arg += outerShadow.offsetX + 'px' + ' ' + outerShadow.offsetY + 'px' + ' '; - var rgba = outerShadow.color; - arg += outerShadow.blurRadius + 'px' + ' 0px ' + _rgbaToFunc(rgba.r, rgba.g, rgba.b, rgba.a); - //query.css('-moz-box-shadow', arg); - //query.css('-wibkit-box-shadow', arg); - //query.css('box-shadow', arg); - //query.css('left', '0px'); - //query.css('top', '0px'); - //query.css({ - // '-moz-box-shadow': arg, - // '-webkit-box-shadow': arg, - // 'box-shadow': arg, - // 'left': '0px', - // 'top': '0px' - //}); - queryCss['-moz-box-shadow'] = arg; - queryCss['-wibkit-box-shadow'] = arg; - queryCss['box-shadow'] = arg; - queryCss['left'] = '0px'; - queryCss['top'] = '0px'; - } - - queryCss['width'] = style.size.width; - queryCss['height'] = style.size.height; - - borderQuery.css(borderQueryCss); - query.css(queryCss); - - //query.css({ width: style.size.width, height: style.size.height }); - }; - - var _rgbaToFunc = function(red, green, blue, alpha) { - return 'rgba(' + red + ',' + green + ',' + blue + ',' + alpha + ')'; - }; - - var _applyImageAndTextJson = function(id, event) { - var textId = $ax.GetTextPanelId(id); - if(textId) _resetTextJson(id, textId); - - // This should never be the case - //if(event != '') { - var imgQuery = $jobj($ax.GetImageIdFromShape(id)); - var e = imgQuery.data('events'); - if(e && e[event]) imgQuery.trigger(event); - - var imageUrl = $ax.adaptive.getImageForStateAndView(id, event); - if(imageUrl) _applyImage(id, imageUrl, event); - - var style = _computeAllOverrides(id, undefined, event, $ax.adaptive.currentViewId); - if(!$.isEmptyObject(style) && textId) _applyTextStyle(textId, style); - - _updateStateClasses( - [ - id, - $ax.repeater.applySuffixToElementId(id, '_div'), - $ax.repeater.applySuffixToElementId(id, '_input') - ], event, true - ); - }; - - let _updateStateClasses = function(ids, event, addMouseOverOnMouseDown) { - for(let i = 0; i < ids.length; i++) { - _updateStateClassesHelper(ids[i], event, addMouseOverOnMouseDown); - } - }; - - let _updateStateClassesHelper = function(id, event, addMouseOverOnMouseDown) { - let jobj = $jobj(id); - - //if(jobj[0] && jobj[0].hasAttribute('widgetwidth')) { - // for (var x = 0; x < jobj[0].children.length; x++) { - // var childId = jobj[0].children[x].id; - // if (childId.indexOf('p') < 0) continue; - - // _updateStateClasses(childId, event) ; - // } - //} else { - - if(event == DISABLED || event == SELECTED) { - let diagramObject = $ax.getObjectFromElementId(id); - if(diagramObject && $ax.public.fn.IsSelectionButton(diagramObject.type)) { - var addSelected = event == DISABLED && jobj.hasClass(SELECTED); - var addDisabled = event == SELECTED && jobj.hasClass(DISABLED); - } - } - for (let i = 0; i < ALL_STATES.length; i++) jobj.removeClass(ALL_STATES[i]); - - if(addMouseOverOnMouseDown && event == MOUSE_DOWN) jobj.addClass(MOUSE_OVER); - if(addSelected) jobj.addClass(SELECTED); - if(addDisabled) jobj.addClass(DISABLED); - if(event != NORMAL) jobj.addClass(event); - //} - }; - - /* ------------------- - - here's the algorithm in a nutshell: - [DOWN] -- refers to navigation down the view inheritance heirarchy (default to most specific) - [UP] -- navigate up the heirarchy - - ComputeAllOverrides (object): - All view styles [DOWN] - If hyperlink - - DO ComputeStateStyle for parent object - - if (MouseOver || MouseDown) - - linkMouseOver Style - - if (MouseDown) - - linkMouseDown style - - ComputeStateStyleForViewChain (parent, STATE) - - if (MouseDown) DO ComputeStateStyleForViewChain for object, mouseOver - DO ComputeStateStyleForViewChain for object, style - - - ComputeStateStyleForViewChain (object, STATE) - FIRST STATE state style [UP] the chain OR default object STATE style - - ------------------- */ - - var FONT_PROPS = { - 'typeface': true, - 'fontName': true, - 'fontWeight': true, - 'fontStyle': true, - 'fontStretch': true, - 'fontSize': true, - 'underline': true, - 'foreGroundFill': true, - 'horizontalAlignment': true, - 'letterCase': true, - 'strikethrough': true - }; - - var _getViewIdChain = $ax.style.getViewIdChain = function(currentViewId, id, diagramObject) { - var viewIdChain; - if (diagramObject.owner.type != 'Axure:Master') { - viewIdChain = $ax.adaptive.getAdaptiveIdChain(currentViewId); - } else { - //set viewIdChain to the chain from the parent RDO - var parentRdoId = $ax('#' + id).getParents(true, ['rdo'])[0][0]; - var rdoState = $ax.style.generateState(parentRdoId); - var rdoStyle = $ax.style.computeFullStyle(parentRdoId, rdoState, currentViewId); - var viewOverride = rdoStyle.viewOverride; - viewIdChain = $ax.adaptive.getMasterAdaptiveIdChain(diagramObject.owner.packageId, viewOverride); - } - return viewIdChain; - } - - var _computeAllOverrides = $ax.style.computeAllOverrides = function(id, parentId, state, currentViewId) { - var computedStyle = {}; - if(parentId) computedStyle = _computeAllOverrides(parentId, null, state, currentViewId); - - var diagramObject = $ax.getObjectFromElementId(id); - - var viewIdChain = _getViewIdChain(currentViewId, id, diagramObject); - var excludeFont = _shapesWithSetRichText[id]; - for(var i = 0; i < viewIdChain.length; i++) { - var viewId = viewIdChain[i]; - var style = diagramObject.adaptiveStyles[viewId]; - if(style) { - // we want to exclude the normal font style for shapes where the rich text has been set with an interaction - // so we copy the style so we don't modify the original, then delete all the font props. - if(excludeFont) { - style = $ax.deepCopy(style); - for(var prop in FONT_PROPS) delete style[prop]; - } - - if(style) { - var customStyle = style.baseStyle && $ax.document.stylesheet.stylesById[style.baseStyle]; - //make sure not to extend the customStyle this can mutate it for future use - $.extend(computedStyle, customStyle); - } - $.extend(computedStyle, style); - } - } - - var currState = NORMAL; - while(currState) { - $.extend(computedStyle, _computeStateStyleForViewChain(diagramObject, currState, viewIdChain, true)); - currState = _unprogressState(currState, state); - } - - return _removeUnsupportedProperties(computedStyle, diagramObject); - }; - - var _computeStateStyleForViewChain = function(diagramObject, state, viewIdChain, excludeNormal) { - var styleObject = diagramObject; - while(styleObject.isContained) styleObject = styleObject.parent; - - var adaptiveStyles = styleObject.adaptiveStyles; - - for(var i = viewIdChain.length - 1; i >= 0; i--) { - var viewId = viewIdChain[i]; - var viewStyle = adaptiveStyles[viewId]; - var stateStyle = viewStyle && _getFullStateStyle(viewStyle, state, excludeNormal); - if (stateStyle) return $.extend({}, stateStyle); - else if (viewStyle && viewStyle.stateStyles) return {}; //stateStyles are overriden but states could be null - } - - // we dont want to actually include the object style because those are not overrides, hence the true for "excludeNormal" and not passing the val through - var stateStyleFromDefault = _getFullStateStyle(styleObject.style, state, true); - return $.extend({}, stateStyleFromDefault); - }; - - // returns the full effective style for an object in a state state and view - var _computeFullStyle = $ax.style.computeFullStyle = function(id, state, currentViewId) { - var obj = $obj(id); - var overrides = _computeAllOverrides(id, undefined, state, currentViewId); - // todo: account for image box - var objStyle = obj.style; - var customStyle = objStyle.baseStyle && $ax.document.stylesheet.stylesById[objStyle.baseStyle]; - var returnVal = $.extend({}, $ax.document.stylesheet.defaultStyle, customStyle, objStyle, overrides); - return _removeUnsupportedProperties(returnVal, obj); - }; - - var _removeUnsupportedProperties = function(style, object) { - // for now all we need to do is remove padding from checkboxes and radio buttons - if ($ax.public.fn.IsRadioButton(object.type) || $ax.public.fn.IsCheckBox(object.type)) { - style.paddingTop = 0; - style.paddingLeft = 0; - style.paddingRight = 0; - style.paddingBottom = 0; - } - if ($ax.public.fn.IsTextBox(object.type) || $ax.public.fn.IsTextArea(object.type) || $ax.public.fn.IsButton(object.type) - || $ax.public.fn.IsListBox(object.type) || $ax.public.fn.IsComboBox(object.type)) { - if (object.images && style.fill) delete style['fill']; - } - - return style; - }; - - var _getFullStateStyle = function(style, state, excludeNormal) { - //'normal' is needed because now DiagramObjects get their image from the Style and unapplying a rollover needs the image - var stateStyle = state == 'normal' && !excludeNormal ? style : style && style.stateStyles && style.stateStyles[state]; - if(stateStyle) { - var customStyle = stateStyle.baseStyle && $ax.document.stylesheet.stylesById[stateStyle.baseStyle]; - //make sure not to extend the customStyle this can mutate it for future use - return $.extend({}, customStyle, stateStyle); - } - return undefined; - }; - - // commented this out for now... we actually will probably need it for ie - var _applyOpacityFromStyle = $ax.style.applyOpacityFromStyle = function(id, style) { - return; - var opacity = style.opacity || ''; - $jobj(id).children().css('opacity', opacity); - }; - - var _initialize = function() { - //$ax.style.initializeObjectTextAlignment($ax('*')); - }; - $ax.style.initialize = _initialize; - - //var _initTextAlignment = function(elementId) { - // var textId = $ax.GetTextPanelId(elementId); - // if(textId) { - // _storeIdToAlignProps(textId); - // // now handle vertical alignment - // if(_getObjVisible(textId)) { - // //_setTextAlignment(textId, _idToAlignProps[textId], false); - // _setTextAlignment(textId); - // } - // } - //}; - - //$ax.style.initializeObjectTextAlignment = function(query) { - // query.filter(function(diagramObject) { - // return $ax.public.fn.IsVector(diagramObject.type) || $ax.public.fn.IsImageBox(diagramObject.type); - // }).each(function(diagramObject, elementId) { - // if($jobj(elementId).length == 0) return; - // _initTextAlignment(elementId); - // }); - //}; - - //$ax.style.initializeObjectTextAlignment = function (query) { - // var textIds = []; - // query.filter(function(diagramObject) { - // return $ax.public.fn.IsVector(diagramObject.type) || $ax.public.fn.IsImageBox(diagramObject.type); - // }).each(function(diagramObject, elementId) { - // if($jobj(elementId).length == 0) return; - // var textId = $ax.GetTextPanelId(elementId); - // if(textId) { - // _storeIdToAlignProps(textId); - // textIds.push(textId); - // } - // }); - - // $ax.style.setTextAlignment(textIds); - //}; - - //var _getPadding = $ax.style.getPadding = function (textId) { - // var shapeId = $ax.GetShapeIdFromText(textId); - // var shapeObj = $obj(shapeId); - // var state = _generateState(shapeId); - - // var style = _computeFullStyle(shapeId, state, $ax.adaptive.currentViewId); - // var vAlign = style.verticalAlignment || 'middle'; - - // var paddingLeft = Number(style.paddingLeft) || 0; - // paddingLeft += (Number(shapeObj && shapeObj.extraLeft) || 0); - // var paddingTop = style.paddingTop || 0; - // var paddingRight = style.paddingRight || 0; - // var paddingBottom = style.paddingBottom || 0; - // return { vAlign: vAlign, paddingLeft: paddingLeft, paddingTop: paddingTop, paddingRight: paddingRight, paddingBottom: paddingBottom }; - //} - - //var _storeIdToAlignProps = function(textId) { - // _idToAlignProps[textId] = _getPadding(textId); - //}; - - var _applyImage = $ax.style.applyImage = function (id, imgUrl, state) { - var object = $obj(id); - if (object.generateCompound) { - for (var i = 0; i < object.compoundChildren.length; i++) { - var componentId = object.compoundChildren[i]; - var childId = $ax.public.fn.getComponentId(id, componentId); - var childImgQuery = $jobj(childId + '_img'); - childImgQuery.attr('src', imgUrl[componentId]); - - _updateStateClasses( - [ - childId + '_img', - childId - ], state, false - ); - } - } else { - var imgQuery = $jobj($ax.GetImageIdFromShape(id)); - //it is hard to tell if setting the image or the class first causing less flashing when adding shadows. - imgQuery.attr('src', imgUrl); - - _updateStateClasses( - [ - id, - $ax.GetImageIdFromShape(id) - ], state, false - ); - if (imgQuery.parents('a.basiclink').length > 0) imgQuery.css('border', 'none'); - } - - }; - - $ax.public.fn.getComponentId = function (id, componentId) { - var idParts = id.split('-'); - idParts[0] = idParts[0] + componentId; - return idParts.join('-'); - } - - var _resetTextJson = function(id, textid) { - // reset the opacity - $jobj(id).children().css('opacity', ''); - - var cacheObject = _originalTextCache[textid]; - if(cacheObject) { - _transformTextWithVerticalAlignment(textid, function() { - var styleCache = cacheObject.styleCache; - var textQuery = $('#' + textid); - textQuery.find('*').each(function(index, element) { - element.style.cssText = styleCache[element.id]; - }); - }); - } - }; - - // Preserves the alingment for the element textid after executing transformFn - - //var _getRtfElementHeight = function(rtfElement) { - // if(rtfElement.innerHTML == '') rtfElement.innerHTML = ' '; - - // // To handle render text as image - // //var images = $(rtfElement).children('img'); - // //if(images.length) return images.height(); - // return rtfElement.offsetHeight; - //}; - - // why microsoft decided to default to round to even is beyond me... - //var _roundToEven = function(number) { - // var numString = number.toString(); - // var parts = numString.split('.'); - // if(parts.length == 1) return number; - // if(parts[1].length == 1 && parts[1] == '5') { - // var wholePart = Number(parts[0]); - // return wholePart % 2 == 0 ? wholePart : wholePart + 1; - // } else return Math.round(number); - //}; - - //var _suspendTextAlignment = 0; - //var _suspendedTextIds = []; - //$ax.style.startSuspendTextAlignment = function() { - // _suspendTextAlignment++; - //} - //$ax.style.resumeSuspendTextAlignment = function () { - // _suspendTextAlignment--; - // if(_suspendTextAlignment == 0) $ax.style.setTextAlignment(_suspendedTextIds); - //} - - var _transformTextWithVerticalAlignment = $ax.style.transformTextWithVerticalAlignment = function(textId, transformFn) { - if(!_originalTextCache[textId]) { - $ax.style.CacheOriginalText(textId); - } - - var rtfElement = window.document.getElementById(textId); - if(!rtfElement) return; - - transformFn(); - - //_storeIdToAlignProps(textId); - - //if (_suspendTextAlignment) { - // _suspendedTextIds.push(textId); - // return; - //} - - //$ax.style.setTextAlignment([textId]); - }; - - // this is for vertical alignments set on hidden objects - //var _idToAlignProps = {}; - - //$ax.style.updateTextAlignmentForVisibility = function (textId) { - // var textObj = $jobj(textId); - // // must check if parent id exists. Doesn't exist for text objs in check boxes, and potentially elsewhere. - // var parentId = textObj.parent().attr('id'); - // if (parentId && $ax.visibility.isContainer(parentId)) return; - - // //var alignProps = _idToAlignProps[textId]; - // //if(!alignProps || !_getObjVisible(textId)) return; - // //if (!alignProps) return; - - // //_setTextAlignment(textId, alignProps); - // _setTextAlignment(textId); - //}; - - var _getObjVisible = _style.getObjVisible = function (id) { - var element = document.getElementById(id); - return element && (element.offsetWidth || element.offsetHeight); - }; - - //$ax.style.setTextAlignment = function (textIds) { - - // var getTextAlignDim = function(textId, alignProps) { - // var dim = {}; - // var vAlign = alignProps.vAlign; - // var paddingTop = Number(alignProps.paddingTop); - // var paddingBottom = Number(alignProps.paddingBottom); - // var paddingLeft = Number(alignProps.paddingLeft); - // var paddingRight = Number(alignProps.paddingRight); - - // var topParam = 0.0; - // var bottomParam = 1.0; - // var leftParam = 0.0; - // var rightParam = 1.0; - - // var textObj = $jobj(textId); - // var textObjParent = textObj.offsetParent(); - // var parentId = textObjParent.attr('id'); - // if(!parentId) { - // // Only case should be for radio/checkbox that get the label now because it must be absolute positioned for animate (offset parent ignored it before) - // textObjParent = textObjParent.parent(); - // parentId = textObjParent.attr('id'); - // } - - // parentId = $ax.visibility.getWidgetFromContainer(textObjParent.attr('id')); - // textObjParent = $jobj(parentId); - // var parentObj = $obj(parentId); - // if(parentObj['bottomTextPadding']) bottomParam = parentObj['bottomTextPadding']; - // if(parentObj['topTextPadding']) topParam = parentObj['topTextPadding']; - // if(parentObj['leftTextPadding']) leftParam = parentObj['leftTextPadding']; - // if(parentObj['rightTextPadding']) rightParam = parentObj['rightTextPadding']; - - // // smart shapes are mutually exclusive from compound vectors. - // var isConnector = parentObj.type == $ax.constants.CONNECTOR_TYPE; - // if(isConnector) return; - - // var axTextObjectParent = $ax('#' + textObjParent.attr('id')); - - - // var jDims = textObj.css(['width','left','top']); - // var oldWidth = $ax.getNumFromPx(jDims['width']); - // var oldLeft = $ax.getNumFromPx(jDims['left']); - // var oldTop = $ax.getNumFromPx(jDims['top']); - - // var newTop = 0; - // var newLeft = 0.0; - - // var size = axTextObjectParent.size(); - // var width = size.width; - // var height = size.height; - // //var width = axTextObjectParent.width(); - // //var height = axTextObjectParent.height(); - - // // If text rotated need to handle getting the correct width for text based on bounding rect of rotated parent. - // var boundingRotation = -$ax.move.getRotationDegreeFromElement(textObj[0]); - // var boundingParent = $axure.fn.getBoundingSizeForRotate(width, height, boundingRotation); - // var extraLeftPadding = (width - boundingParent.width) / 2; - // width = boundingParent.width; - // var relativeTop = 0.0; - // relativeTop = height * topParam; - // var containerHeight = height * bottomParam - relativeTop; - - // newLeft = paddingLeft + extraLeftPadding + width * leftParam; - - // var newWidth = width * (rightParam - leftParam) - paddingLeft - paddingRight; - - // var horizChange = newWidth != oldWidth || newLeft != oldLeft; - // if(horizChange) { - // dim.left = newLeft; - // dim.width = newWidth; - // //textObj.css('left', newLeft); - // //textObj.width(newWidth); - // } - - // var textHeight = _getRtfElementHeight(textObj[0]); - - // if(vAlign == "middle") - // newTop = _roundToEven(relativeTop + (containerHeight - textHeight + paddingTop - paddingBottom) / 2); - // else if(vAlign == "bottom") - // newTop = _roundToEven(relativeTop + containerHeight - textHeight - paddingBottom); - // else newTop = _roundToEven(paddingTop + relativeTop); - // var vertChange = oldTop != newTop; - // if (vertChange) dim.top = newTop; //textObj.css('top', newTop + 'px'); - - // return dim; - // }; - - // var applyTextAlignment = function(textId, dim) { - // var textObj = $jobj(textId); - // if(dim.left) { - // textObj.css('left', dim.left); - // textObj.width(dim.width); - // } - // if(dim.top) textObj.css('top', dim.top); - - // if((dim.top || dim.left)) _updateTransformOrigin(textId); - // }; - - // var idToDim = []; - // for (var i = 0; i < textIds.length; i++) { - // var textId = textIds[i]; - // var alignProps = _idToAlignProps[textId]; - // if (!alignProps || !_getObjVisible(textId)) continue; - - // idToDim.push({ id: textId, dim: getTextAlignDim(textId, alignProps) }); - // } - - // for (var i = 0; i < idToDim.length; i++) { - // var info = idToDim[i]; - // applyTextAlignment(info.id, info.dim); - // } - //}; - - //var _setTextAlignment = function(textId, alignProps, updateProps) { - // if(updateProps) _storeIdToAlignProps(textId); - // if(!alignProps) return; - - // var vAlign = alignProps.vAlign; - // var paddingTop = Number(alignProps.paddingTop); - // var paddingBottom = Number(alignProps.paddingBottom); - // var paddingLeft = Number(alignProps.paddingLeft); - // var paddingRight = Number(alignProps.paddingRight); - - // var topParam = 0.0; - // var bottomParam = 1.0; - // var leftParam = 0.0; - // var rightParam = 1.0; - - // var textObj = $jobj(textId); - // var textObjParent = textObj.offsetParent(); - // var parentId = textObjParent.attr('id'); - // var isConnector = false; - // if(parentId) { - // parentId = $ax.visibility.getWidgetFromContainer(textObjParent.attr('id')); - // textObjParent = $jobj(parentId); - // var parentObj = $obj(parentId); - // if(parentObj['bottomTextPadding']) bottomParam = parentObj['bottomTextPadding']; - // if(parentObj['topTextPadding']) topParam = parentObj['topTextPadding']; - // if(parentObj['leftTextPadding']) leftParam = parentObj['leftTextPadding']; - // if(parentObj['rightTextPadding']) rightParam = parentObj['rightTextPadding']; - - // // smart shapes are mutually exclusive from compound vectors. - // isConnector = parentObj.type == $ax.constants.CONNECTOR_TYPE; - // } - // if(isConnector) return; - - // var axTextObjectParent = $ax('#' + textObjParent.attr('id')); - - // var oldWidth = $ax.getNumFromPx(textObj.css('width')); - // var oldLeft = $ax.getNumFromPx(textObj.css('left')); - // var oldTop = $ax.getNumFromPx(textObj.css('top')); - - // var newTop = 0; - // var newLeft = 0.0; - - // var width = axTextObjectParent.width(); - // var height = axTextObjectParent.height(); - - // // If text rotated need to handle getting the correct width for text based on bounding rect of rotated parent. - // var boundingRotation = -$ax.move.getRotationDegreeFromElement(textObj[0]); - // var boundingParent = $axure.fn.getBoundingSizeForRotate(width, height, boundingRotation); - // var extraLeftPadding = (width - boundingParent.width) / 2; - // width = boundingParent.width; - // var relativeTop = 0.0; - // relativeTop = height * topParam; - // var containerHeight = height * bottomParam - relativeTop; - - - // newLeft = paddingLeft + extraLeftPadding + width * leftParam; - - // var newWidth = width * (rightParam - leftParam) - paddingLeft - paddingRight; - - // var horizChange = newWidth != oldWidth || newLeft != oldLeft; - // if(horizChange) { - // textObj.css('left', newLeft); - // textObj.width(newWidth); - // } - - // var textHeight = _getRtfElementHeight(textObj[0]); - - // if(vAlign == "middle") newTop = _roundToEven(relativeTop + (containerHeight - textHeight + paddingTop - paddingBottom) / 2); - // else if(vAlign == "bottom") newTop = _roundToEven(relativeTop + containerHeight - textHeight - paddingBottom); - // else newTop = _roundToEven(paddingTop + relativeTop); - // var vertChange = oldTop != newTop; - // if(vertChange) textObj.css('top', newTop + 'px'); - - // if((vertChange || horizChange)) _updateTransformOrigin(textId); - //}; - - //var _updateTransformOrigin = function (textId) { - // var textObj = $jobj(textId); - // var parentId = textObj.parent().attr('id'); - // if(!$obj(parentId).hasTransformOrigin) return; - - // //var transformOrigin = textObj.css('-webkit-transform-origin') || - // // textObj.css('-moz-transform-origin') || - // // textObj.css('-ms-transform-origin') || - // // textObj.css('transform-origin'); - // //if(transformOrigin) { - // var textObjParent = $ax('#' + textObj.parent().attr('id')); - // var newX = (textObjParent.width() / 2 - $ax.getNumFromPx(textObj.css('left'))); - // var newY = (textObjParent.height() / 2 - $ax.getNumFromPx(textObj.css('top'))); - // var newOrigin = newX + 'px ' + newY + 'px'; - // textObj.css('-webkit-transform-origin', newOrigin); - // textObj.css('-moz-transform-origin', newOrigin); - // textObj.css('-ms-transform-origin', newOrigin); - // textObj.css('transform-origin', newOrigin); - // //} - //}; - - $ax.style.reselectElements = function() { - for(var id in _selectedWidgets) { - // Only looking for the selected widgets that don't have their class set - if(!_selectedWidgets[id] || $jobj(id).hasClass('selected')) continue; - - $jobj(id).addClass('selected'); - _applyImageAndTextJson(id, $ax.style.generateState(id)); - } - - for(id in _disabledWidgets) { - // Only looking for the disabled widgets that don't have their class yet - if (!_disabledWidgets[id] || $jobj(id).hasClass('disabled')) continue; - - $jobj(id).addClass('disabled'); - _applyImageAndTextJson(id, $ax.style.generateState(id)); - } - } - - $ax.style.clearStateForRepeater = function(repeaterId) { - var children = $ax.getChildElementIdsForRepeater(repeaterId); - for(var i = 0; i < children.length; i++) { - var id = children[i]; - delete _selectedWidgets[id]; - delete _disabledWidgets[id]; - } - } - - _style.updateStateClass = function (repeaterId) { - var subElementIds = $ax.getChildElementIdsForRepeater(repeaterId); - for (var i = 0; i < subElementIds.length; i++) { - _applyImageAndTextJson(subElementIds[i], $ax.style.generateState(subElementIds[i])); - } - } - - $ax.style.clearAdaptiveStyles = function() { - for(var shapeId in _adaptiveStyledWidgets) { - var repeaterId = $ax.getParentRepeaterFromScriptId(shapeId); - if(repeaterId) continue; - var elementId = $ax.GetButtonShapeId(shapeId); - if(elementId) _applyImageAndTextJson(elementId, $ax.style.generateState(elementId)); - } - - _adaptiveStyledWidgets = {}; - }; - - $ax.style.setAdaptiveStyle = function(shapeId, style) { - _adaptiveStyledWidgets[$ax.repeater.getScriptIdFromElementId(shapeId)] = style; - - var textId = $ax.GetTextPanelId(shapeId); - if(textId) _applyTextStyle(textId, style); - - $ax.placeholderManager.refreshPlaceholder(shapeId); - - // removing this for now - // if(style.location) { - // $jobj(shapeId).css('top', style.location.x + "px") - // .css('left', style.location.y + "px"); - // } - }; - - //------------------------------------------------------------------------- - // _applyTextStyle - // - // Applies a rollover style to a text element. - // id : the id of the text object to set. - // styleProperties : an object mapping style properties to values. eg: - // { 'fontWeight' : 'bold', - // 'fontStyle' : 'italic' } - //------------------------------------------------------------------------- - var _applyTextStyle = function(id, style) { - _transformTextWithVerticalAlignment(id, function() { - var styleProperties = _getCssStyleProperties(style); - $('#' + id).find('*').each(function(index, element) { - _applyCssProps(element, styleProperties); - }); - }); - }; - - var _applyCssProps = function(element, styleProperties, applyAllStyle) { - if(applyAllStyle) { - var allProps = styleProperties.allProps; - for(var prop in allProps) element.style[prop] = allProps[prop]; - } else { - var nodeName = element.nodeName.toLowerCase(); - if(nodeName == 'p') { - var parProps = styleProperties.parProps; - for(prop in parProps) element.style[prop] = parProps[prop]; - } else if(nodeName != 'a') { - var runProps = styleProperties.runProps; - for(prop in runProps) element.style[prop] = runProps[prop]; - } - } - }; - - var _getCssShadow = function(shadow) { - return !shadow.on ? "none" - : shadow.offsetX + "px " + shadow.offsetY + "px " + shadow.blurRadius + "px " + _getCssColor(shadow.color); - }; - - var _getCssStyleProperties = function(style) { - var toApply = {}; - toApply.runProps = {}; - toApply.parProps = {}; - toApply.allProps = {}; - - if(style.fontName) toApply.allProps.fontFamily = toApply.runProps.fontFamily = style.fontName; - // we need to set font size on both runs and pars because otherwise it well mess up the measure and thereby vertical alignment - if(style.fontSize) toApply.allProps.fontSize = toApply.runProps.fontSize = toApply.parProps.fontSize = style.fontSize; - if(style.fontWeight !== undefined) toApply.allProps.fontWeight = toApply.runProps.fontWeight = style.fontWeight; - if(style.fontStyle !== undefined) toApply.allProps.fontStyle = toApply.runProps.fontStyle = style.fontStyle; - - var textDecoration = []; - if(style.underline !== undefined) textDecoration[0] = style.underline ? 'underline ' : 'none'; - if(style.strikethrough !== undefined) { - var index = textDecoration.length; - if(style.strikethrough) textDecoration[index] ='line-through'; - else if(index == 0) textDecoration[0] = 'none'; - } - if (textDecoration.length > 0) { - var decorationLineUp = ""; - for (var l = 0; l < textDecoration.length; l++) { - decorationLineUp = decorationLineUp + textDecoration[l]; - } - toApply.allProps.textDecoration = toApply.runProps.textDecoration = decorationLineUp; - } - if(style.foreGroundFill) { - toApply.allProps.color = toApply.runProps.color = _getColorFromFill(style.foreGroundFill); - //if(style.foreGroundFill.opacity) toApply.allProps.opacity = toApply.runProps.opacity = style.foreGroundFill.opacity; - } - if(style.horizontalAlignment) toApply.allProps.textAlign = toApply.parProps.textAlign = toApply.runProps.textAlign = style.horizontalAlignment; - if(style.lineSpacing) toApply.allProps.lineHeight = toApply.parProps.lineHeight = style.lineSpacing; - if(style.textShadow) toApply.allProps.textShadow = toApply.parProps.textShadow = _getCssShadow(style.textShadow); - if (style.letterCase) toApply.allProps.textTransform = toApply.parProps.textTransform = style.letterCase; - if (style.characterSpacing) toApply.allProps.letterSpacing = toApply.runProps.letterSpacing = style.characterSpacing; - - return toApply; - }; - - var _getColorFromFill = function(fill) { - //var fillString = '00000' + fill.color.toString(16); - //return '#' + fillString.substring(fillString.length - 6); - var val = fill.color; - var color = {}; - color.b = val % 256; - val = Math.floor(val / 256); - color.g = val % 256; - val = Math.floor(val / 256); - color.r = val % 256; - color.a = typeof (fill.opacity) == 'number' ? fill.opacity : 1; - return _getCssColor(color); - }; - - var _getCssColor = function(rgbaObj) { - return "rgba(" + rgbaObj.r + ", " + rgbaObj.g + ", " + rgbaObj.b + ", " + rgbaObj.a + ")"; - }; - - // //-------------------------------------------------------------------------- - // // ApplyStyleRecursive - // // - // // Applies a style recursively to all span and div tags including elementNode - // // and all of its children. - // // - // // element : the element to apply the style to - // // styleName : the name of the style property to set (eg. 'font-weight') - // // styleValue : the value of the style to set (eg. 'bold') - // //-------------------------------------------------------------------------- - // function ApplyStyleRecursive(element, styleName, styleValue) { - // var nodeName = element.nodeName.toLowerCase(); - - // if (nodeName == 'div' || nodeName == 'span' || nodeName == 'p') { - // element.style[styleName] = styleValue; - // } - - // for (var i = 0; i < element.childNodes.length; i++) { - // ApplyStyleRecursive(element.childNodes[i], styleName, styleValue); - // } - // } - - // //--------------------------------------------------------------------------- - // // ApplyTextProperty - // // - // // Applies a text property to rtfElement. - // // - // // rtfElement : the the root text element of the rtf object (this is the - // // element named <id>_rtf - // // prop : the style property to set. - // // value : the style value to set. - // //--------------------------------------------------------------------------- - // function ApplyTextProperty(rtfElement, prop, value) { - // /* - // var oldHtml = rtfElement.innerHTML; - // if (prop == 'fontWeight') { - // rtfElement.innerHTML = oldHtml.replace(/< *b *\/?>/gi, ""); - // } else if (prop == 'fontStyle') { - // rtfElement.innerHTML = oldHtml.replace(/< *i *\/?>/gi, ""); - // } else if (prop == 'textDecoration') { - // rtfElement.innerHTML = oldHtml.replace(/< *u *\/?>/gi, ""); - // } - // */ - - // for (var i = 0; i < rtfElement.childNodes.length; i++) { - // ApplyStyleRecursive(rtfElement.childNodes[i], prop, value); - // } - // } - //} - - //--------------------------------------------------------------------------- - // GetAndCacheOriginalText - // - // Gets the html for the pre-rollover state and returns the Html representing - // the Rich text. - //--------------------------------------------------------------------------- - var CACHE_COUNTER = 0; - - $ax.style.CacheOriginalText = function(textId, hasRichTextBeenSet) { - var rtfQuery = $('#' + textId); - if(rtfQuery.length > 0) { - - var styleCache = {}; - rtfQuery.find('*').each(function(index, element) { - var elementId = element.id; - if(!elementId) element.id = elementId = 'cache' + CACHE_COUNTER++; - styleCache[elementId] = element.style.cssText; - }); - - _originalTextCache[textId] = { - styleCache: styleCache - }; - if(hasRichTextBeenSet) { - var shapeId = $ax.GetShapeIdFromText(textId); - _shapesWithSetRichText[shapeId] = true; - } - } - }; - - $ax.style.ClearCacheForRepeater = function(repeaterId) { - for(var elementId in _originalTextCache) { - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - if($ax.getParentRepeaterFromScriptId(scriptId) == repeaterId) delete _originalTextCache[elementId]; - } - }; - - - - $ax.style.prefetch = function() { - var scriptIds = $ax.getAllScriptIds(); - var image = new Image(); - for(var i = 0; i < scriptIds.length; i++) { - var obj = $obj(scriptIds[i]); - if (!$ax.public.fn.IsImageBox(obj.type)) continue; - var images = obj.images; - for (var key in images) image.src = images[key]; - - var imageOverrides = obj.imageOverrides; - for(var elementId in imageOverrides) { - var override = imageOverrides[elementId]; - for (var state in override) { - _addImageOverride(elementId, state, override[state]); - image.src = override[state]; - } - } - } - }; -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/tree.js b/web/main/static/resources/scripts/axure/tree.js deleted file mode 100644 index 7c5ca2d..0000000 --- a/web/main/static/resources/scripts/axure/tree.js +++ /dev/null @@ -1,189 +0,0 @@ -// This is actually for BOTH trees and menus -$axure.internal(function($ax) { - var _tree = $ax.tree = {}; - var _menu = $ax.menu = {}; - - $ax.menu.InitializeSubmenu = function(subMenuId, cellId) { - var $submenudiv = $('#' + subMenuId); - - //mouseenter and leave for parent table cell - $('#' + cellId).mouseenter(function(e) { - //show current submenu -// var submenuElement = document.getElementById(subMenuId); -// if($ax.visibility.IsVisible(submenuElement) && submenuElement.style.display !== 'none') return; - $ax.visibility.SetIdVisible(subMenuId, true); - $ax.legacy.BringToFront(subMenuId); - //$submenudiv.find('.menu_item').each(function() { - // $ax.style.updateTextAlignmentForVisibility($ax.GetTextPanelId($(this).attr('id'))); - //}); - _fireEventForSubmenu(subMenuId, "onShow"); - - }).mouseleave(function (e) { - var offset = $submenudiv.offset(); - var subcontwidth = $submenudiv.width(); - var subcontheight = $submenudiv.height(); - //If mouse is not within the submenu (added 3 pixel margin to top and left calculations), then close the submenu... - if(e.pageX + 3 < offset.left || e.pageX > offset.left + subcontwidth || e.pageY + 3 < offset.top || e.pageY > offset.top + subcontheight) { - $submenudiv.find('.sub_menu').addBack().each(function () { -// if(!$ax.visibility.IsVisible(this)) return; - $ax.visibility.SetVisible(this, false); - _fireEventForSubmenu(subMenuId, "onHide"); - }); - $ax.style.SetWidgetHover(cellId, false); - } - }); - - $submenudiv.css('display', 'none'); - - //mouseleave for submenu - $submenudiv.mouseleave(function(e) { - //close this menu and all menus below it - $(this).find('.sub_menu').addBack().css({ 'visibility': 'hidden', 'display': 'none' }).each(function () { -// if(!$ax.visibility.IsVisible(this)) return; - _fireEventForSubmenu(this.id, "onHide"); - }); - $ax.style.SetWidgetHover(cellId, false); - }); - }; - - var _fireEventForSubmenu = function(targetId, eventName) { - var diagramObject = $ax.getObjectFromElementId(targetId); - var event = diagramObject.interactionMap && diagramObject.interactionMap[eventName]; - if(event) { - var eventInfo = $ax.getEventInfoFromEvent($ax.getjBrowserEvent(), false, targetId); - $ax.event.handleEvent(targetId, eventInfo, event, false, true); - } - } - - function IsNodeVisible(nodeId) { - var current = window.document.getElementById(nodeId); - var parent = current.parentNode; - - //move all the parent's children that are below the node and their annotations - while(!$(current).hasClass("treeroot")) { - if(!$ax.visibility.IsVisible(parent)) return false; - current = parent; - parent = parent.parentNode; - } - return true; - } - - $ax.tree.ExpandNode = function(nodeId, childContainerId, plusMinusId) { - var container = window.document.getElementById(childContainerId); - if(!container || $ax.visibility.IsVisible(container)) return; - $ax.visibility.SetVisible(container, true); - - if(plusMinusId != '') $ax.style.SetWidgetSelected(plusMinusId, true); - - var delta = _getExpandCollapseDelta(nodeId, childContainerId); - - var isVisible = IsNodeVisible(nodeId); - var current = window.document.getElementById(nodeId); - var parent = current.parentNode; - - //move all the parent's children that are below the node and their annotations - while(!$(current).hasClass("treeroot")) { - var after = false; - var i = 0; - for(i = 0; i < parent.childNodes.length; i++) { - var child = parent.childNodes[i]; - if(after && child.id && $(child).hasClass("treenode")) { - var elementId = child.id; - child.style.top = $ax.getNumFromPx($(child).css('top')) + delta + 'px'; - var ann = window.document.getElementById(elementId + "_ann"); - if (ann) ann.style.top = $ax.getNumFromPx($(ann).css('top')) + delta + 'px'; - } - if(child == current) after = true; - } - current = parent; - parent = parent.parentNode; - if(!isVisible && $ax.visibility.IsVisible(parent)) break; - } - }; - - $ax.tree.CollapseNode = function(nodeId, childContainerId, plusMinusId) { - var container = window.document.getElementById(childContainerId); - if(!container || !$ax.visibility.IsVisible(container)) return; - - if(plusMinusId != '') $ax.style.SetWidgetSelected(plusMinusId, false); - - var delta = _getExpandCollapseDelta(nodeId, childContainerId); - - //hide it after getting the delta, otherwise the delta can't be calculated (offsetParent is null) - $ax.visibility.SetVisible(container, false); - - var isVisible = IsNodeVisible(nodeId); - var current = window.document.getElementById(nodeId); - var parent = current.parentNode; - - //move all the parent's children that are below the node and their annotations - while(!$(current).hasClass("treeroot")) { - var after = false; - var i = 0; - for(i = 0; i < parent.childNodes.length; i++) { - var child = parent.childNodes[i]; - if(after && child.id && $(child).hasClass("treenode")) { - var elementId = child.id; - child.style.top = $ax.getNumFromPx($(child).css('top')) - delta + 'px'; - var ann = window.document.getElementById(elementId + "_ann"); - if (ann) ann.style.top = $ax.getNumFromPx($(ann).css('top')) - delta + 'px'; - } - if(child == current) after = true; - } - current = parent; - parent = current.parentNode; - if(!isVisible && $ax.visibility.IsVisible(parent)) break; - } - }; - - var _getExpandCollapseDelta = function(nodeId, childContainerId) { - return _getChildContainerHeightHelper(childContainerId); - }; - - var _getChildContainerHeightHelper = function(childContainerId) { - var height = 0; - $('#' + childContainerId).children().each(function() { - if($(this).hasClass("treenode")) { - height += $(this).height(); - var subContainer = window.document.getElementById(this.id + '_children'); - if(subContainer && $ax.visibility.IsVisible(subContainer)) { - height += _getChildContainerHeightHelper(subContainer.id); - } - } - }); - return height; - }; - - $ax.tree.InitializeTreeNode = function(nodeId, plusminusid, childContainerId, selectText) { - var childContainer = window.document.getElementById(childContainerId); - if(childContainer) { - //relying on the html generator to put this inline so we know to collapse by default - var isCollapsed = childContainer.style.visibility == "hidden"; - if(isCollapsed) $ax.visibility.SetVisible(childContainer, false); - - if(!isCollapsed && plusminusid != '') $ax.style.SetWidgetSelected(plusminusid, true); - } - - if(plusminusid != '') { - $jobj(plusminusid).click(function() { - var visibleSet = $ax.visibility.IsIdVisible(childContainerId); - - if(visibleSet) $ax.tree.CollapseNode(nodeId, childContainerId, plusminusid); - else $ax.tree.ExpandNode(nodeId, childContainerId, plusminusid); - $ax.tree.SelectTreeNode(nodeId, true); - - return false; - }).css('cursor', 'default'); - } - }; - - var _getButtonShapeId = function(id) { - var obj = $obj(id); - return $ax.public.fn.IsTreeNodeObject(obj.type) ? $ax.getElementIdFromPath([obj.buttonShapeId], { relativeTo: id }) : id; - }; - - $ax.tree.SelectTreeNode = function(id, selected) { - $ax.style.SetWidgetSelected(_getButtonShapeId(id), selected); - }; - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/utils.temp.js b/web/main/static/resources/scripts/axure/utils.temp.js deleted file mode 100644 index 43ba542..0000000 --- a/web/main/static/resources/scripts/axure/utils.temp.js +++ /dev/null @@ -1,99 +0,0 @@ -// ******* Deep Copy ******** // -$axure.internal(function($ax) { - // TODO: [ben] Ah, infinite loops cause major issues here. Tried saving objects we've already hit, but that didn't seem to work (at least at my first shot). - // TODO: [ben] To continue from above, added a filter to filter out problem keys. Will need a better way of sorting this out eventually. - var _deepCopy = function (original, trackCopies, filter) { - if(trackCopies) { - var index = _getCopyIndex(original); - if(index != -1) return _originalToCopy[index][1]; - } - var isArray = original instanceof Array; - var isObject = !(original instanceof Function) && !(original instanceof Date) && (original instanceof Object); - if(!isArray && !isObject) return original; - var copy = isArray ? [] : { }; - if(trackCopies) _originalToCopy.push([original, copy]); - isArray ? deepCopyArray(original, trackCopies, copy, filter) : deepCopyObject(original, trackCopies, copy, filter); - return copy; - }; - $ax.deepCopy = _deepCopy; - - // Hacky way to copy event info. Copying dragInfo causes major issues due to infinite loops - // Hashmap doesn't map objects well. It just toStrings them, making them all the same key. This has to be slow... - var _originalToCopy = []; - var _getCopyIndex = function(original) { - for(var i = 0; i < _originalToCopy.length; i++) if(original === _originalToCopy[i][0]) return i; - return -1; - }; - - $ax.eventCopy = function(eventInfo) { - var copy = _deepCopy(eventInfo, true, ['dragInfo', 'elementQuery', 'obj']); - // reset the map. TODO: May need to reset elsewhere too, but this is the only way it's used currently - _originalToCopy = []; - - return copy; - }; - - var deepCopyArray = function(original, trackCopies, copy, filter) { - for(var i = 0; i < original.length; i++) { - copy[i] = _deepCopy(original[i], trackCopies, filter); - } - }; - - var deepCopyObject = function(original, trackCopies, copy, filter) { - for(var key in original) { - if(!original.hasOwnProperty(key)) continue; // Continue if the prop was not put there like a dictionary, but just a native part of the object - - if(filter && filter.indexOf[key] != -1) copy[key] = original[key]; // If that key is filtered out, skip recursion on it. - else copy[key] = _deepCopy(original[key], trackCopies, filter); - } - }; - - // Our implementation of splice because it is broken in IE8... - $ax.splice = function(array, startIndex, count) { - var retval = []; - if(startIndex >= array.length || startIndex < 0 || count == 0) return retval; - if(!count || startIndex + count > array.length) count = array.length - startIndex; - for(var i = 0; i < count; i++) retval[i] = array[startIndex + i]; - for(i = startIndex + count; i < array.length; i++) array[i - count] = array[i]; - for(i = 0; i < count; i++) array.pop(); - return retval; - }; -}); - - - -// ******* Flow Shape Links ******** // -$axure.internal(function($ax) { - - $(window.document).ready(function() { - if (!$ax.document.configuration.linkFlowsToPages && !$ax.document.configuration.linkFlowsToPagesNewWindow) return; - - $ax(function (dObj) { return ($ax.public.fn.IsVector(dObj.type) || $ax.public.fn.IsSnapshot(dObj.type)) && dObj.referencePageUrl; }).each(function (dObj, elementId) { - - var elementIdQuery = $('#' + elementId); - - if($ax.document.configuration.linkFlowsToPages && !$ax.event.HasClick(dObj)) { - elementIdQuery.css("cursor", "pointer"); - elementIdQuery.click(function() { - $ax.navigate({ - url: dObj.referencePageUrl, - target: "current", - includeVariables: true - }); - }); - } - - if($ax.document.configuration.linkFlowsToPagesNewWindow) { - $('#' + elementId + "_ref").append("<div id='" + elementId + "PagePopup' class='refpageimage'></div>"); - $('#' + elementId + "PagePopup").click(function() { - $ax.navigate({ - url: dObj.referencePageUrl, - target: "new", - includeVariables: true - }); - }); - } - }); - }); - -}); diff --git a/web/main/static/resources/scripts/axure/variables.js b/web/main/static/resources/scripts/axure/variables.js deleted file mode 100644 index 7839bdd..0000000 --- a/web/main/static/resources/scripts/axure/variables.js +++ /dev/null @@ -1,136 +0,0 @@ -// ******* GLOBAL VARIABLE PROVIDER ******** // -$axure.internal(function($ax) { - var _globalVariableValues = {}; - - var _globalVariableProvider = {}; - $ax.globalVariableProvider = _globalVariableProvider; - - var setVariableValue = function(variable, value, suppressBroadcast) { - if(!(value instanceof Object)) value = value.toString(); - - variable = variable.toLowerCase(); - _globalVariableValues[variable] = value; - - if(suppressBroadcast !== true) { - var varData = { - globalVarName: variable, - globalVarValue: value.toString() - }; - - $axure.messageCenter.postMessage('setGlobalVar', varData); - } - - //Post global var values only if pageData is loaded (suppresses exception which occurs when page loads) - if($ax.pageData) { - _postGlobalVarVals(); - } - }; - _globalVariableProvider.setVariableValue = setVariableValue; - - var getVariableValue = function(variable, eventInfo, ignoreDefaultsForLinkUrl) { - variable = variable.toLowerCase(); - if(_globalVariableValues[variable] !== undefined) { - //If this is for the GetLinkUrl function and - //the current value of the global variable is the same as the default defined in the document, don't return it - if(ignoreDefaultsForLinkUrl == true && $ax.document.globalVariables[variable] == _globalVariableValues[variable]) { - return null; - } - - return _globalVariableValues[variable]; - } - if($ax.document.globalVariables[variable] !== undefined) return ignoreDefaultsForLinkUrl == true ? null : $ax.document.globalVariables[variable]; - switch(variable) { - case "pagename": return $ax.pageData.page.name; - - case "now": return eventInfo.now; - case "gendate": return $ax.pageData.generationDate; - - case "dragx": return $ax.drag.GetDragX(); - case "dragy": return $ax.drag.GetDragY(); - case "totaldragx": return $ax.drag.GetTotalDragX(); - case "totaldragy": return $ax.drag.GetTotalDragY(); - case "dragtime": return $ax.drag.GetDragTime(); - - case "math": return Math; - case "date": return Date; - - case "window": return eventInfo && eventInfo.window; - case "this": return eventInfo && eventInfo.thiswidget && $ax.getWidgetInfo(eventInfo.thiswidget.elementId); - case "item": return (eventInfo && eventInfo.item && eventInfo.item.valid && eventInfo.item) || getVariableValue('targetitem', eventInfo, ignoreDefaultsForLinkUrl); - case "targetitem": return eventInfo && eventInfo.targetElement && $ax.getItemInfo(eventInfo.targetElement); - case "repeater": return eventInfo && eventInfo.repeater; - case "target": return eventInfo && eventInfo.targetElement && $ax.getWidgetInfo(eventInfo.targetElement); - case "cursor": return eventInfo && eventInfo.cursor; - default: - var gen = variable.substr(0, 3) == "gen"; - var date = gen ? $ax.pageData.generationDate : new Date(); - var prop = gen ? variable.substr(3) : variable; - switch(prop) { - case "day": return date.getDate(); - case "month": return date.getMonth() + 1; - case "monthname": return $ax.getMonthName(date.getMonth()); - case "dayofweek": return $ax.getDayOfWeek(date.getDay()); - case "year": return date.getFullYear(); - case "time": return date.toLocaleTimeString(); - case "hours": return date.getHours(); - case "minutes": return date.getMinutes(); - case "seconds": return date.getSeconds(); - default: return ''; - } - } - }; - _globalVariableProvider.getVariableValue = getVariableValue; - - var load = function() { - let query = (window.location.href.split("#")[1] || ''); //hash.substring(1); Firefox decodes this so & in variables breaks - if(query.length > 0) { - $ax.utils.parseGlobalVars(query, setVariableValue); - } - }; - - var getLinkUrl = function(baseUrl, useGlobalVarName) { - var toAdd = ''; - var definedVariables = _getDefinedVariables(); - for(var i = 0; i < definedVariables.length; i++) { - var key = definedVariables[i]; - var val = getVariableValue(key, undefined, true); - if(val != null) { - if(toAdd.length > 0) toAdd += '&'; - else if(useGlobalVarName) toAdd = GLOBAL_VAR_NAME; - toAdd += key + '=' + encodeURIComponent(val); - } - } - return toAdd.length > 0 ? baseUrl + (useGlobalVarName ? '' : $axure.shouldSendVarsToServer() ? '?' : '#') + toAdd + "&" + GLOBAL_VAR_CHECKSUM + "=1" : baseUrl; - }; - _globalVariableProvider.getLinkUrl = getLinkUrl; - - var _getDefinedVariables = function() { - return $ax.pageData.variables; - }; - _globalVariableProvider.getDefinedVariables = _getDefinedVariables; - - var _postGlobalVarVals = function() { - var retVal = {}; - var definedVariables = _getDefinedVariables(); - for(var i = 0; i < definedVariables.length; i++) { - var key = definedVariables[i]; - var val = getVariableValue(key); - if(val != null) { - retVal[key] = val; - } - } - - $ax.messageCenter.postMessage('globalVariableValues', retVal); - }; - - $ax.messageCenter.addMessageListener(function(message, data) { - if(message == 'getGlobalVariables') { - _postGlobalVarVals(); - } else if(message == 'resetGlobalVariables') { - _globalVariableValues = {}; - _postGlobalVarVals(); - } - }); - - load(); -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/viewer.js b/web/main/static/resources/scripts/axure/viewer.js deleted file mode 100644 index 10415e4..0000000 --- a/web/main/static/resources/scripts/axure/viewer.js +++ /dev/null @@ -1,268 +0,0 @@ -// ******* SITEMAP TOOLBAR VIEWER ACTIONS ******** // -$axure.internal(function ($ax) { - var userTriggeredEventNames = ['onClick', 'onDoubleClick', 'onMouseOver', 'onMouseMove', 'onMouseOut', 'onMouseDown', 'onMouseUp', - 'onKeyDown', 'onKeyUp', 'onFocus', 'onLostFocus', 'onTextChange', 'onSelectionChange', 'onSelectedChange', 'onSelect', 'onUnselect', - 'onSwipeLeft', 'onSwipeRight', 'onSwipeUp', 'onSwipeDown', 'onDragStart', 'onDrag', 'onDragDrop', 'onScroll', 'onContextMenu', 'onMouseHover', 'onLongClick']; - - //var _toggleSelectWidgetNoteForRepeater = function (repeaterId, scriptId, select) { - // var itemIds = $ax.getItemIdsForRepeater(repeaterId); - - // for(var i = 0; i < itemIds.length; i++) { - // var itemId = itemIds[i]; - // var elementId = $ax.repeater.createElementId(scriptId, itemId); - // if(select) $('#' + elementId).addClass('widgetNoteSelected'); - // else $('#' + elementId).removeClass('widgetNoteSelected'); - // } - //} - $ax.messageCenter.addMessageListener(function (message, data) { - //If annotation toggle message received from sitemap, toggle footnotes - if(message == 'toggleSelectWidgetNote') { - - if (!IOS) { - $('.widgetNoteSelected').removeClass('widgetNoteSelected'); - } - - if(!data.value) return; - - //if(lastSelectedWidgetNote == data.id) { - // lastSelectedWidgetNote = null; - // return; - //} - - $ax('*').each(function(obj, elementId) { - if (obj.id == data.id) { - if (!IOS) { - $('#' + elementId).addClass('widgetNoteSelected'); - } - - _scrollToSelectedNote($('#' + elementId), data.view); - } - }); - } - }); - - var _scrollToSelectedNote = function ($elmt, view) { - var isLandscape = IOS ? window.orientation != 0 && window.orientation != 180 : false; - var winWidth = !IOS ? $(window).width() : (isLandscape ? window.screen.height : window.screen.width) - view.panelWidthOffset; - var winHeight = !IOS ? $(window).height() : view.height; - var docLeft = $('html').last().scrollLeft(); - var docTop = $('html').last().scrollTop(); - var docRight = docLeft + winWidth; - var docBottom = docTop + winHeight; - - var scale = $('#base').css('transform');; - scale = (scale == "none") ? 1 : Number(scale.substring(scale.indexOf('(') + 1, scale.indexOf(','))); - - var bodyLeft = ($('body').css('left') !== undefined && $('body').css('left') !== "auto") ? Number($('body').css('left').replace('px','')) : 0; - var top = scale * Number($elmt.css('top').replace('px', '')); - var bottom = top + scale * $elmt.height(); - var left = scale * Number($elmt.css('left').replace('px', '')) + bodyLeft; - var right = left + scale * $elmt.width(); - - var doHorizontalMove = left < docLeft || right > docRight; - var doVerticalMove = top < docTop || bottom > docBottom; - var padding = scale * 50; - - var newScrollLeft = 0 - if (left < docLeft) { - newScrollLeft = left - padding; - } else if (right > docRight) { - newScrollLeft = right + padding - winWidth; - } - - var newScrollTop = 0 - if (top < docTop) { - newScrollTop = top - padding; - } else if (bottom > docBottom) { - newScrollTop = bottom + padding - winHeight; - } - - // Device Frame or Scale to width or Scale to fit (situations where there is no horizontal scroll) - if (view.h || view.scaleVal == 1 || view.scaleVal == 2) { - doHorizontalMove = false; - } - - // Has Device Frame or Scale to Width and widget with note is outside of viewable panel right bounds - if ((view.scaleVal == 1 || view.h) && (left > docRight)) { - doVerticalMove = false; - } - - // TODO: need to do something for dynamic panel with scroll - if (doHorizontalMove && doVerticalMove) { - $("html, body").animate({ scrollLeft: newScrollLeft, scrollTop: newScrollTop }, 300); - } else if (doHorizontalMove) { - $("html, body").animate({ scrollLeft: newScrollLeft }, 300); - } else if (doVerticalMove) { - $("html, body").animate({ scrollTop: newScrollTop }, 300); - } - } - - var highlightEnabled = false; - $ax.messageCenter.addMessageListener(function(message, data) { - if(message == 'highlightInteractive') { - highlightEnabled = data == true; - _applyHighlight($ax('*')); - } - }); - - var _applyHighlight = $ax.applyHighlight = function(query, ignoreUnset) { - if(ignoreUnset && !highlightEnabled) return; - - var pulsateClassName = 'legacyPulsateBorder'; - //Determine if the widget has a defined userTriggeredEventName specified in the array above - var _isInteractive = function(diagramObject) { - if(diagramObject && diagramObject.interactionMap) { - for(var index in userTriggeredEventNames) { - if(diagramObject.interactionMap[userTriggeredEventNames[index]]) return true; - } - } - return false; - }; - - //Traverse through parent layers (if any) of an element and see if any have a defined userTriggeredEventName - var _findMatchInParent = function(id) { - var parents = $ax('#' + id).getParents(true, ['layer'])[0]; - for(var i in parents) { - var parentId = parents[i]; - var parentObj = $ax.getObjectFromScriptId(parentId); - if(_isInteractive(parentObj)) return true; - } - return false; - }; - - //Find all widgets with a defined userTriggeredEventName specified in the array above - var $matchingElements = query.filter(function (obj, id) { - - //This prevents the top left corner of the page from highlighting with everything else - if($ax.public.fn.IsLayer(obj.type)) return false; - - if(_isInteractive(obj)) return true; - else if($ax.public.fn.IsVector(obj.type) && obj.referencePageUrl) return true; - - //Last check on the object's parent layer(s), if a layer has a defined userTriggeredEventName - //then we shall highlight each member of that layer TODO This is a design decision and is subject to change - return _findMatchInParent(id); - }).$(); - - var isHighlighted = $matchingElements.is('.' + pulsateClassName); - - //Toggle the pulsate class on the matched elements - if(highlightEnabled && !isHighlighted) { - $matchingElements.addClass(pulsateClassName); - } else if(!highlightEnabled && isHighlighted) { - $matchingElements.removeClass(pulsateClassName); - } - }; - - var getElementsFromPoint = function (x, y) { - var elementsFromPointFn = document.elementsFromPoint || document.msElementsFromPoint; - if (typeof elementsFromPointFn === "function") { - return elementsFromPointFn.bind(document)(x, y); - } - return []; - } - - $axure.getIdAndRectAtLoc = function (data) { - var element = document.elementFromPoint(data.x, data.y); - if (!element) return undefined; - - var jObj = _getElementIdFromTarget(element); - if (jObj.length > 0) { - var id = jObj.attr('id'); - var axObj = $ax('#' + id); - var rect = axObj.pageBoundingRect(); - return { 'id': id, 'rect': rect }; - } - return undefined; - } - - $axure.getListOfIdAndRectAtLoc = function (data) { - var domElements = getElementsFromPoint(data.x, data.y); - - if (!domElements || !domElements.length) return []; - - const elements = []; - - domElements.forEach(function (domElement) { - var jObj = _getElementIdFromTarget(domElement); - if (jObj.length > 0) { - var id = jObj.attr('id'); - var axObj = $ax('#' + id); - var rect = axObj.pageBoundingRect(); - if (elements.findIndex(function (x) { return x.id === id }) < 0) { - elements.push( { 'id': id, 'rect': rect } ); - } - } - }); - - return elements; - } - - $axure.getIdRectAndStyleAtLoc = function(data) { - var element = document.elementFromPoint(data.x, data.y); - if (!element) return undefined; - - var jObj = _getElementIdFromTarget(element); - if (jObj.length > 0) { - var id = jObj.attr('id'); - return $axure.getRectAndStyleById(id); - } - return undefined; - } - - $axure.getListOfIdRectAndStyleAtLoc = function(data) { - var domElements = getElementsFromPoint(data.x, data.y); - - if (!domElements || !domElements.length) return []; - - const elements = []; - - domElements.forEach(function (domElement) { - var jObj = _getElementIdFromTarget(domElement); - if (jObj.length > 0) { - var id = jObj.attr('id'); - if (elements.findIndex(function (x) { return x.id === id }) < 0) { - elements.push($axure.getRectAndStyleById(id)); - } - } - }); - - return elements; - } - - $axure.getRectAndStyleById = function (id) { - var axObj = $ax('#' + id); - var rect = axObj.pageBoundingRect(); - var style = $ax.style.computeFullStyle(id, $ax.style.generateState(id), $ax.adaptive.currentViewId); - style.text = axObj.text(); - return { 'id': id, 'rect': rect, 'style': style }; - } - - $axure.isIdVisible = function (id) { - return id ? $ax.visibility.IsIdVisible(id) : false; - } - - $axure.getParentElementById = function (elementId) { - if (!elementId) return undefined; - var parentId = $ax.getLayerParentFromElementId(elementId); - if (!parentId) { - return undefined; - } - return $axure.getRectAndStyleById(parentId); - } - - var _getElementIdFromTarget = function (target) { - var targetId = target.id; - var jTarget = $(target); - while((!targetId || targetId.indexOf('cache') > -1) && jTarget[0].tagName != 'HTML') { - jTarget = jTarget.parent(); - targetId = jTarget.attr('id'); - } - if(targetId && targetId != 'base') { - var sections = targetId.split('_'); - return $('#' + sections[0]); - } - return ''; - } - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/axure/visibility.js b/web/main/static/resources/scripts/axure/visibility.js deleted file mode 100644 index 9df0cd9..0000000 --- a/web/main/static/resources/scripts/axure/visibility.js +++ /dev/null @@ -1,1315 +0,0 @@ -$axure.internal(function($ax) { - var document = window.document; - var _visibility = {}; - $ax.visibility = _visibility; - - var _defaultHidden = {}; - var _defaultLimbo = {}; - - // ****************** Visibility and State Functions ****************** // - - var _isIdVisible = $ax.visibility.IsIdVisible = function(id) { - return $ax.visibility.IsVisible(window.document.getElementById(id)); - }; - - $ax.visibility.IsVisible = function(element) { - //cannot use css('visibility') because that gets the effective visiblity - //e.g. won't be able to set visibility on panels inside hidden panels - return element.style.visibility != 'hidden'; - }; - - $ax.visibility.SetIdVisible = function(id, visible) { - $ax.visibility.SetVisible(window.document.getElementById(id), visible); - // Hide lightbox if necessary - if(!visible) { - $jobj($ax.repeater.applySuffixToElementId(id, '_lightbox')).remove(); - $ax.flyoutManager.unregisterPanel(id, true); - } - }; - - var _setAllVisible = function(query, visible) { - for(var i = 0; i < query.length; i++) { - _visibility.SetVisible(query[i], visible); - } - } - - $ax.visibility.SetVisible = function (element, visible) { - //not setting display to none to optimize measuring - if(visible) { - if($(element).hasClass(HIDDEN_CLASS)) $(element).removeClass(HIDDEN_CLASS); - if($(element).hasClass(UNPLACED_CLASS)) $(element).removeClass(UNPLACED_CLASS); - element.style.display = ''; - element.style.visibility = 'inherit'; - } else { - element.style.display = 'none'; - element.style.visibility = 'hidden'; - } - }; - - var _setWidgetVisibility = $ax.visibility.SetWidgetVisibility = function (elementId, options) { - var visible = $ax.visibility.IsIdVisible(elementId); - // If limboed, just fire the next action then leave. - if(visible == options.value || _limboIds[elementId]) { - if(!_limboIds[elementId]) options.onComplete && options.onComplete(); - $ax.action.fireAnimationFromQueue(elementId, $ax.action.queueTypes.fade); - return; - } - - options.containInner = true; - var query = $jobj(elementId); - var parentId = query.parent().attr('id'); - var axObj = $obj(elementId); - var preserveScroll = false; - var isPanel = $ax.public.fn.IsDynamicPanel(axObj.type); - var isLayer = $ax.public.fn.IsLayer(axObj.type); - if(!options.noContainer && (isPanel || isLayer)) { - //if dp has scrollbar, save its scroll position - if(isPanel && axObj.scrollbars != 'none') { - var shownState = $ax.dynamicPanelManager.getShownState(elementId); - preserveScroll = true; - //before hiding, try to save scroll location - if(!options.value && shownState) { - DPStateAndScroll[elementId] = { - shownId: shownState.attr('id'), - left: shownState.scrollLeft(), - top: shownState.scrollTop() - } - } - } - - _pushContainer(elementId, isPanel); - if(isPanel && !options.value) _tryResumeScrollForDP(elementId); - var complete = options.onComplete; - options.onComplete = function () { - if(complete) complete(); - _popContainer(elementId, isPanel); - //using containers stops mouseleave from firing on IE/Edge and FireFox - if(!options.value && $ax.event.mouseOverObjectId && (FIREFOX || $axure.browser.isEdge || IE)) { - var mouseOveredElement = $('#' + $ax.event.mouseOverObjectId); - if(mouseOveredElement && !mouseOveredElement.is(":visible")) { - var axObj = $obj($ax.event.mouseOverObjectId); - - if(($ax.public.fn.IsDynamicPanel(axObj.type) || $ax.public.fn.IsLayer(axObj.type)) && axObj.propagate) { - mouseOveredElement.trigger('mouseleave'); - } else mouseOveredElement.trigger('mouseleave.ixStyle'); - } - } - //after showing dp, restore the scoll position - if(isPanel && options.value) _tryResumeScrollForDP(elementId, true); - } - options.containerExists = true; - } - _setVisibility(parentId, elementId, options, preserveScroll); - - //set the visibility of the annotation box as well if it exists - var ann = document.getElementById(elementId + "_ann"); - if(ann) _visibility.SetVisible(ann, options.value); - - //set ref visibility for ref of flow shape, if that exists - var ref = document.getElementById(elementId + '_ref'); - if(ref) _visibility.SetVisible(ref, options.value); - - if(options.value && !MOBILE_DEVICE && $ax.adaptive.isDeviceMode()) _updateMobileScrollForWidgetShown(axObj); - }; - - var _updateMobileScrollForWidgetShown = function(widget) { - var isPanel = $ax.public.fn.IsDynamicPanel(widget.type); - var isLayer = $ax.public.fn.IsLayer(widget.type); - if (isPanel) { - var elementId = $id(widget); - var stateId = $ax.repeater.applySuffixToElementId(elementId, '_state0'); - $ax.dynamicPanelManager.updateMobileScroll(elementId, stateId, true); - if (!widget.diagrams) return; - for (var i = 0; i < widget.diagrams.length; ++i) { - var diagram = widget.diagrams[i]; - if (!diagram.objects) continue; - for (var j = 0; j < diagram.objects.length; ++j) { - _updateMobileScrollForWidgetShown(diagram.objects[j]); - } - } - } else if (isLayer) { - for (var i = 0; i < widget.objs.length; ++i) { - _updateMobileScrollForWidgetShown(widget.objs[i]); - } - } - } - - var _setVisibility = function(parentId, childId, options, preserveScroll) { - var wrapped = $jobj(childId); - var completeTotal = 1; - var visible = $ax.visibility.IsIdVisible(childId); - - if(visible == options.value) { - options.onComplete && options.onComplete(); - $ax.action.fireAnimationFromQueue(childId, $ax.action.queueTypes.fade); - return; - } - - var child = $jobj(childId); - var size = options.size || (options.containerExists ? $(child.children()[0]) : child); - - var isIdFitToContent = $ax.dynamicPanelManager.isIdFitToContent(parentId); - //fade and resize won't work together when there is a container... but we still needs the container for fit to content DPs - var needContainer = options.easing && options.easing != 'none' && (options.easing != 'fade' || isIdFitToContent); - var cullPosition = options.cull ? options.cull.css('position') : ''; - var containerExists = options.containerExists; - - var isFullWidth = $ax.dynamicPanelManager.isPercentWidthPanel($obj(childId)); - - // If fixed fit to content panel, then we must set size on it. It will be size of 0 otherwise, because container in it is absolute position. - var needSetSize = false; - var sizeObj = {}; - if(needContainer) { - var sizeId = ''; - if($ax.dynamicPanelManager.isIdFitToContent(childId)) sizeId = childId; - else { - var panelId = $ax.repeater.removeSuffixFromElementId(childId); - if($ax.dynamicPanelManager.isIdFitToContent(panelId)) sizeId = panelId; - } - - if(sizeId) { - needSetSize = true; - - sizeObj = $jobj(sizeId); - var newSize = options.cull || sizeObj; - var newAxSize = $ax('#' + newSize.attr('id')); - sizeObj.width(newAxSize.width()); - sizeObj.height(newAxSize.height()); - } - } - - var wrappedOffset = { left: 0, top: 0 }; - var visibleWrapped = wrapped; - if(needContainer) { - var childObj = $obj(childId); - if (options.cull) { - var axCull = $ax('#' + options.cull.attr('id')); - var containerWidth = axCull.width(); - var containerHeight = axCull.height(); - } else { - if (childObj && ($ax.public.fn.IsLayer(childObj.type))) {// || childObj.generateCompound)) { - var boundingRectangle = $ax('#' + childId).offsetBoundingRect(); - //var boundingRectangle = $ax.public.fn.getWidgetBoundingRect(childId); - wrappedOffset.left = boundingRectangle.left; - wrappedOffset.top = boundingRectangle.top; - containerWidth = boundingRectangle.width; - containerHeight = boundingRectangle.height; - } else if (childObj && childObj.generateCompound) { - var image = $jobj(childId + '_img'); - containerWidth = $ax.getNumFromPx(image.css('width')); - containerHeight = $ax.getNumFromPx(image.css('height')); - wrappedOffset.left = $ax.getNumFromPx(image.css('left')); - wrappedOffset.top = $ax.getNumFromPx(image.css('top')); - } else { - containerWidth = $ax('#' + childId).width(); - containerHeight = $ax('#' + childId).height(); - } - } - - var containerId = $ax.visibility.applyWidgetContainer(childId); -// var container = _makeContainer(containerId, options.cull || boundingRectangle, isFullWidth, options.easing == 'flip', wrappedOffset, options.containerExists); - var container = _makeContainer(containerId, containerWidth, containerHeight, isFullWidth, options.easing == 'flip', wrappedOffset, options.containerExists); - - if(options.containInner) { - wrapped = _wrappedChildren(containerExists ? $(child.children()[0]) : child); - - // Filter for visibile wrapped children - visibleWrapped = []; - for (var i = 0; i < wrapped.length; i++) if($ax.visibility.IsVisible(wrapped[i])) visibleWrapped.push(wrapped[i]); - visibleWrapped = $(visibleWrapped); - - completeTotal = visibleWrapped.length; - if(!containerExists) container.prependTo(child); - - // Offset items if necessary - if(!containerExists && (wrappedOffset.left != 0 || wrappedOffset.top != 0)) { - for(var i = 0; i < wrapped.length; i++) { - var inner = $(wrapped[i]); - inner.css('left', $ax.getNumFromPx(inner.css('left')) - wrappedOffset.left); - inner.css('top', $ax.getNumFromPx(inner.css('top')) - wrappedOffset.top); - // Parent layer is now size 0, so have to have to use conatiner since it's the real size. - // Should we use container all the time? This may make things easier for fit panels too. - size = container; - } - } - } else if(!containerExists) container.insertBefore(child); - if(!containerExists) wrapped.appendTo(container); - - if (options.value && options.containInner) { - //has to set children first because flip to show needs children invisible - _setAllVisible(visibleWrapped, false); - //_updateChildAlignment(childId); - _setAllVisible(child, true); - } - } - - var completeCount = 0; - var onComplete = function () { - completeCount++; - if (needContainer && completeCount == completeTotal) { - if ($ax.public.fn.isCompoundVectorHtml(container.parent()[0])) { - wrappedOffset.left = $ax.getNumFromPx(container.css('left')); - wrappedOffset.top = $ax.getNumFromPx(container.css('top')); - } - - if (options.containInner && !containerExists) { - if (wrappedOffset.left != 0 || wrappedOffset.top != 0) { - for (i = 0; i < wrapped.length; i++) { - inner = $(wrapped[i]); - if (!inner.hasClass('text')) { - inner.css('left', $ax.getNumFromPx(inner.css('left')) + wrappedOffset.left); - inner.css('top', $ax.getNumFromPx(inner.css('top')) + wrappedOffset.top); - } - } - } - - wrapped.filter('.text').css({ 'left': '', 'top': '' }); - } - - if(options.containInner && !options.value) { - _setAllVisible(child, false); - _setAllVisible(visibleWrapped, true); - } - - if(containerExists) { - if(!options.settingChild) container.css('position', 'relative;'); - } else { - wrapped.insertBefore(container); - container.remove(); - } - - if(childObj && $ax.public.fn.IsDynamicPanel(childObj.type) && window.modifiedDynamicPanleParentOverflowProp) { - child.css('overflow', 'hidden'); - window.modifiedDynamicPanleParentOverflowProp = false; - } - } - - //if(options.value) _updateChildAlignment(childId); - - if(!needContainer || completeTotal == completeCount) { - if(options.cull) options.cull.css('position', cullPosition); - - if(needSetSize) { - sizeObj.css('width', 'auto'); - sizeObj.css('height', 'auto'); - } - - options.onComplete && options.onComplete(); - - if(options.fire) { - $ax.event.raiseSyntheticEvent(childId, options.value ? 'onShow' : 'onHide'); - $ax.action.fireAnimationFromQueue(childId, $ax.action.queueTypes.fade); - } - } - }; - - // Nothing actually being animated, all wrapped elements invisible - if(!visibleWrapped.length) { - if(!options.easing || options.easing == 'none') { - $ax.visibility.SetIdVisible(childId, options.value); - completeTotal = 1; - onComplete(); - } else { - window.setTimeout(function() { - completeCount = completeTotal - 1; - onComplete(); - },options.duration); - } - - return; - } - - if(!options.easing || options.easing == 'none') { - $ax.visibility.SetIdVisible(childId, options.value); - completeTotal = 1; - onComplete(); - } else if(options.easing == 'fade') { - if(options.value) { - if(preserveScroll) { - visibleWrapped.css('opacity', 0); - visibleWrapped.css('visibility', 'inherit'); - visibleWrapped.css('display', 'block'); - //was hoping we could just use fadein here, but need to set display before set scroll position - _tryResumeScrollForDP(childId); - visibleWrapped.animate({ opacity: 1 }, { - duration: options.duration, - easing: 'swing', - queue: false, - complete: function() { - $ax.visibility.SetIdVisible(childId, true); - visibleWrapped.css('opacity', ''); - onComplete(); - } - }); - } else { - // Can't use $ax.visibility.SetIdVisible, because we only want to set visible, we don't want to set display, fadeIn will handle that. - visibleWrapped.css('visibility', 'inherit'); - visibleWrapped.fadeIn({ - queue: false, - duration: options.duration, - complete: onComplete - }); - } - } else { - // Fading here is being strange... - visibleWrapped.animate({ opacity: 0 }, { duration: options.duration, easing: 'swing', queue: false, complete: function() { - $ax.visibility.SetIdVisible(childId, false); - visibleWrapped.css('opacity', ''); - - onComplete(); - }}); - } - } else if (options.easing == 'flip') { - //this container will hold - var trapScroll = _trapScrollLoc(childId); - var innerContainer = $('<div></div>'); - innerContainer.attr('id', containerId + "_inner"); - innerContainer.data('flip', options.direction == 'left' || options.direction == 'right' ? 'y' : 'x'); - innerContainer.css({ - position: 'relative', - 'width': containerWidth, - 'height': containerHeight, - 'display': 'flex' - }); - - innerContainer.appendTo(container); - wrapped.appendTo(innerContainer); - - if(childObj && $ax.public.fn.IsDynamicPanel(childObj.type)) var containerDiv = child; - else containerDiv = parentId ? $jobj(parentId) : child.parent(); - - completeTotal = 1; - var flipdegree; - - var originForFlip = containerWidth / 2 + 'px ' + containerHeight / 2 + 'px'; - if (options.value) { - innerContainer.css({ - '-webkit-transform-origin': originForFlip, - '-ms-transform-origin': originForFlip, - 'transform-origin': originForFlip, - }); - - //options.value == true means in or show, note to get here, the element must be currently hidden to show, - // we need to first flip it +/- 90deg without animation (180 if we want to show the back of the flip) - switch(options.direction) { - case 'right': - case 'left': - _setRotateTransformation(innerContainer, _getRotateString(true, options.direction === 'right', options.showFlipBack)); - flipdegree = 'rotateY(0deg)'; - break; - case 'up': - case 'down': - _setRotateTransformation(innerContainer, _getRotateString(false, options.direction === 'up', options.showFlipBack)); - flipdegree = 'rotateX(0deg)'; - break; - } - - var onFlipShowComplete = function() { - var trapScroll = _trapScrollLoc(childId); - $ax.visibility.SetIdVisible(childId, true); - - wrapped.insertBefore(innerContainer); - innerContainer.remove(); - trapScroll(); - - onComplete(); - }; - - innerContainer.css({ - '-webkit-backface-visibility': 'hidden', - 'backface-visibility': 'hidden' - }); - - child.css({ - 'display': '', - 'visibility': 'inherit' - }); - - visibleWrapped.css({ - 'display': '', - 'visibility': 'inherit' - }); - - innerContainer.css({ - '-webkit-transition-duration': options.duration + 'ms', - 'transition-duration': options.duration + 'ms' - }); - - if(preserveScroll) _tryResumeScrollForDP(childId); - _setRotateTransformation(innerContainer, flipdegree, containerDiv, onFlipShowComplete, options.duration, true); - } else { //hide or out - innerContainer.css({ - '-webkit-transform-origin': originForFlip, - '-ms-transform-origin': originForFlip, - 'transform-origin': originForFlip, - }); - switch(options.direction) { - case 'right': - case 'left': - flipdegree = _getRotateString(true, options.direction !== 'right', options.showFlipBack); - break; - case 'up': - case 'down': - flipdegree = _getRotateString(false, options.direction !== 'up', options.showFlipBack); - break; - } - - var onFlipHideComplete = function() { - var trapScroll = _trapScrollLoc(childId); - wrapped.insertBefore(innerContainer); - $ax.visibility.SetIdVisible(childId, false); - - innerContainer.remove(); - trapScroll(); - - onComplete(); - }; - - innerContainer.css({ - '-webkit-backface-visibility': 'hidden', - 'backface-visibility': 'hidden', - '-webkit-transition-duration': options.duration + 'ms', - 'transition-duration': options.duration + 'ms' - }); - - if(preserveScroll) _tryResumeScrollForDP(childId); - _setRotateTransformation(innerContainer, flipdegree, containerDiv, onFlipHideComplete, options.duration, true); - } - - trapScroll(); - } else { - // Because the move is gonna fire on annotation and ref too, need to update complete total - completeTotal = $addAll(visibleWrapped, childId).length; - if(options.value) { - _slideStateIn(childId, childId, options, size, false, onComplete, visibleWrapped, preserveScroll); - } else { - var tops = []; - var lefts = []; - for(var i = 0; i < visibleWrapped.length; i++) { - var currWrapped = $(visibleWrapped[i]); - - tops.push(fixAuto(currWrapped, 'top')); - lefts.push(fixAuto(currWrapped, 'left')); - } - - var onOutComplete = function () { - //bring back SetIdVisible on childId for hiding lightbox - $ax.visibility.SetIdVisible(childId, false); - for(i = 0; i < visibleWrapped.length; i++) { - currWrapped = $(visibleWrapped[i]); - $ax.visibility.SetVisible(currWrapped[0], false); - currWrapped.css('top', tops[i]); - currWrapped.css('left', lefts[i]); - } - onComplete(); - }; - _slideStateOut(size, childId, options, onOutComplete, visibleWrapped); - } - } - - // If showing, go through all rich text objects inside you, and try to redo alignment of them - //if(options.value && !options.containInner) { - // _updateChildAlignment(childId); - //} - }; - - // IE/Safari are giving auto here instead of calculating to for us. May need to calculate this eventually, but for now we can assume auto === 0px for the edge case found - var fixAuto = function (jobj, prop) { - var val = jobj.css(prop); - return val == 'auto' ? '0px' : val; - }; - - var _getRotateString = function (y, neg, showFlipBack) { - // y means flip on y axis, or left/right, neg means flipping it left/down, and show back is for set panel state - // and will show the back of the widget (transparent) for the first half of a show, or second half of a hide. - return 'rotate' + (y ? 'Y' : 'X') + '(' + (neg ? '-' : '') + (showFlipBack ? 180 : IE ? 91 : 90) + 'deg)'; - } - - //var _updateChildAlignment = function(childId) { - // var descendants = $jobj(childId).find('.text'); - // for(var i = 0; i < descendants.length; i++) $ax.style.updateTextAlignmentForVisibility(descendants[i].id); - //}; - var _wrappedChildren = function (child) { - return child.children(); - //var children = child.children(); - //var valid = []; - //for(var i = 0; i < children.length; i++) if($ax.visibility.IsVisible(children[i])) valid.push(children[i]); - //return $(valid); - }; - - var requestAnimationFrame = window.requestAnimationFrame || - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || window.msRequestAnimationFrame || - function (callback) { - window.setTimeout(callback, 1000 / 60); - }; - - var _setRotateTransformation = function(elementsToSet, transformValue, elementParent, flipCompleteCallback, flipDurationMs, useAnimationFrame) { - if(flipCompleteCallback) { - //here we didn't use 'transitionend' event to fire callback - //when show/hide on one element, changing transition property will stop the event from firing - window.setTimeout(flipCompleteCallback, flipDurationMs); - } - - var trasformCss = { - '-webkit-transform': transformValue, - '-moz-transform': transformValue, - '-ms-transform': transformValue, - '-o-transform': transformValue, - 'transform': transformValue - }; - - if(useAnimationFrame) { - if(FIREFOX || CHROME) $('body').hide().show(0); //forces FF to render the animation - requestAnimationFrame(function() { - elementsToSet.css(trasformCss); - }); - } else elementsToSet.css(trasformCss); - - //when deal with dynamic panel, we need to set it's parent's overflow to visible to have the 3d effect - //NOTE: we need to set this back when both flips finishes in DP, to prevents one animation finished first and set this back - if(elementParent && elementParent.css('overflow') === 'hidden') { - elementParent.css('overflow', 'visible'); - window.modifiedDynamicPanleParentOverflowProp = true; - } - }; - - $ax.visibility.GetPanelState = function(id) { - var children = $ax.visibility.getRealChildren($jobj(id).children()); - for(var i = 0; i < children.length; i++) { - if(children[i].style && $ax.visibility.IsVisible(children[i])) return children[i].id; - } - return ''; - }; - - var containerCount = {}; - $ax.visibility.SetPanelState = function(id, stateId, easingOut, directionOut, durationOut, easingIn, directionIn, durationIn, showWhenSet) { - var show = !$ax.visibility.IsIdVisible(id) && showWhenSet; - if(show) $ax.visibility.SetIdVisible(id, true); - - // Exit here if already at desired state. - if($ax.visibility.IsIdVisible(stateId)) { - if(show) { - $ax.event.raiseSyntheticEvent(id, 'onShow'); - // If showing size changes and need to update parent panels - $ax.dynamicPanelManager.fitParentPanel(id); - } - - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.setState); - return; - } - - var hasEasing = easingIn != 'none' || easingOut != 'none'; - if(hasEasing) _pushContainer(id, true); - - var state = $jobj(stateId); - var oldStateId = $ax.visibility.GetPanelState(id); - var oldState = $jobj(oldStateId); - - var isFixed = $jobj(id).css('position') == 'fixed'; - //pin to browser - if(isFixed) $ax.dynamicPanelManager.adjustFixed(id, oldState.width(), oldState.height(), state.width(), state.height()); - - _bringPanelStateToFront(id, stateId, oldStateId, easingIn == 'none' || durationIn == '0'); - - var fitToContent = $ax.dynamicPanelManager.isIdFitToContent(id); - var resized = false; - if(fitToContent) { - // Set resized - //var width = state.width(); - //var height = state.height(); - var newBoundingRect = $ax('#' + stateId).childrenBoundingRect(); - var width = newBoundingRect.right; - var height = newBoundingRect.bottom; - var oldBoundingRect = $ax('#' + id).size(); - var oldWidth = oldBoundingRect.right; - var oldHeight = oldBoundingRect.bottom; - resized = width != oldWidth || height != oldHeight; - //resized = width != oldState.width() || height != oldState.height(); - - $ax.visibility.setResizedSize(id, $obj(id).percentWidth ? oldWidth : width, height); - } - - //edge case for sliding - var movement = (directionOut == 'left' || directionOut == 'up' || state.children().length == 0) && oldState.children().length != 0 ? oldState : state; - var onCompleteCount = 0; - var onComplete = function () { - //move this call from _setVisibility() for animate out. - //Because this will make the order of dp divs consistence: the showing panel is always in front after both animation finished - //tested in the cases where one panel is out/show slower/faster/same time/instantly. - _bringPanelStateToFront(id, stateId, oldStateId, false); - - if (window.modifiedDynamicPanleParentOverflowProp) { - var parent = id ? $jobj(id) : child.parent(); - parent.css('overflow', 'hidden'); - window.modifiedDynamicPanleParentOverflowProp = false; - } - - $ax.dynamicPanelManager.fitParentPanel(id); - $ax.dynamicPanelManager.updatePanelPercentWidth(id); - $ax.dynamicPanelManager.updatePanelContentPercentWidth(id); - $ax.action.fireAnimationFromQueue(id, $ax.action.queueTypes.setState); - $ax.event.raiseSyntheticEvent(id, "onPanelStateChange"); - $ax.event.leavingState(oldStateId); - if (hasEasing) _popContainer(id, true); - - $ax.dynamicPanelManager.updateMobileScroll(id, stateId, true); - }; - // Must do state out first, so if we cull by new state, location is correct - _setVisibility(id, oldStateId, { - value: false, - easing: easingOut, - direction: directionOut, - duration: durationOut, - containerExists: true, - onComplete: function() { -// if(easingIn !== 'flip') _bringPanelStateToFront(id, stateId); - if (++onCompleteCount == 2) onComplete(); - }, - settingChild: true, - size: movement, - //cull for - cull: easingOut == 'none' || state.children().length == 0 ? oldState : state, - showFlipBack: true - }); - - _setVisibility(id, stateId, { - value: true, - easing: easingIn, - direction: directionIn, - duration: durationIn, - containerExists: true, - onComplete: function () { -// if (easingIn === 'flip') _bringPanelStateToFront(id, stateId); - if (++onCompleteCount == 2) onComplete(); - }, - settingChild: true, - //size for offset - size: movement, - showFlipBack: true - }); - - if(show) $ax.event.raiseSyntheticEvent(id, 'onShow'); - if(resized) $ax.event.raiseSyntheticEvent(id, 'onResize'); - }; - - var containedFixed = {}; - var _pushContainer = _visibility.pushContainer = function(id, panel) { - var count = containerCount[id]; - if(count) containerCount[id] = count + 1; - else { - var trapScroll = _trapScrollLoc(id); - var jobj = $jobj(id); - var children = jobj.children(); - var css = { - position: 'relative', - top: 0, - left: 0 - }; - - if(!panel) { - var boundingRect = $ax('#' + id).offsetBoundingRect(); - //var boundingRect = $axure.fn.getWidgetBoundingRect(id); - css.top = boundingRect.top; - css.left = boundingRect.left; - } - - var container = $('<div></div>'); - container.attr('id', ''); // Placeholder id, so we won't try to recurse the container until it is ready - container.css(css); - //container.append(jobj.children()); - jobj.append(container); - containerCount[id] = 1; - - // Panel needs to wrap children - if(panel) { - for(var i = 0; i < children.length; i++) { - var child = $(children[i]); - var childContainer = $('<div></div>'); - childContainer.attr('id', $ax.visibility.applyWidgetContainer(child.attr('id'))); - childContainer.css(css); - child.after(childContainer); - childContainer.append(child); - container.append(childContainer); - } - } else { - var focus = _getCurrFocus(); - if(focus) $ax.event.addSuppressedEvent($ax.repeater.removeSuffixFromElementId(focus), 'OnLostFocus'); - - // Layer needs to fix top left - var childIds = $ax('#' + id).getChildren()[0].children; - for(var i = 0; i < childIds.length; i++) { - var childId = childIds[i]; - var childObj = $jobj(childId); - var fixedInfo = $ax.dynamicPanelManager.getFixedInfo(childId); - if(fixedInfo.fixed) { - var axObj = $ax('#' + childId); - var viewportLocation = axObj.viewportLocation(); - var left = viewportLocation.left; - var top = viewportLocation.top; - //var left = axObj.left(); - //var top = axObj.top(); - containedFixed[childId] = { left: left, top: top, fixed: fixedInfo }; - childObj.css('left', left); - childObj.css('top', top); - childObj.css('margin-left', 0); - childObj.css('margin-top', 0); - childObj.css('right', 'auto'); - childObj.css('bottom', 'auto'); - childObj.css('position', 'absolute'); - } - var cssChange = { - left: '-=' + css.left, - top: '-=' + css.top - }; - if($ax.getTypeFromElementId(childId) == $ax.constants.LAYER_TYPE) { - _pushContainer(childId, false); - $ax.visibility.applyWidgetContainer(childId, true).css(cssChange); - } else { - //if ($ax.public.fn.isCompoundVectorHtml(jobj[0])) { - // var grandChildren = jobj[0].children; - // //while (grandChildren.length > 0 && grandChildren[0].id.indexOf('container') >= 0) grandChildren = grandChildren[0].children; - - // for (var j = 0; j < grandChildren.length; j++) { - // var grandChildId = grandChildren[j].id; - // if (grandChildId.indexOf(childId + 'p') >= 0 || grandChildId.indexOf('_container') >= 0) $jobj(grandChildId).css(cssChange); - // } - //} else - // Need to include ann and ref in move. - childObj = $addAll(childObj, childId); - childObj.css(cssChange); - } - - container.append(childObj); - } - _setCurrFocus(focus); - } - container.attr('id', $ax.visibility.applyWidgetContainer(id)); // Setting the correct final id for the container - trapScroll(); - } - }; - - var _popContainer = _visibility.popContainer = function (id, panel) { - var count = containerCount[id]; - if(!count) return; - count--; - containerCount[id] = count; - if(count != 0) return; - - var trapScroll = _trapScrollLoc(id); - - var jobj = $jobj(id); - var container = $ax.visibility.applyWidgetContainer(id, true); - - // If layer is at bottom or right of page, unwrapping could change scroll by temporarily reducting page size. - // To avoid this, we let container persist on page, with the size it is at this point, and don't remove container completely - // until the children are back to their proper locations. - var size = $ax('#' + id).size(); - container.css('width', size.width); - container.css('height', size.height); - var focus = _getCurrFocus(); - if(focus) $ax.event.addSuppressedEvent($ax.repeater.removeSuffixFromElementId(focus), 'OnLostFocus'); - jobj.append(container.children()); - _setCurrFocus(focus); - $('body').first().append(container); - - // Layer doesn't have children containers to clean up - if(panel) { - var children = jobj.children(); - for(var i = 0; i < children.length; i++) { - var childContainer = $(children[i]); - var child = $(childContainer.children()[0]); - childContainer.after(child); - childContainer.remove(); - } - } else { - var left = container.css('left'); - var top = container.css('top'); - var childIds = $ax('#' + id).getChildren()[0].children; - for (var i = 0; i < childIds.length; i++) { - var childId = childIds[i]; - var cssChange = { - left: '+=' + left, - top: '+=' + top - }; - if($ax.getTypeFromElementId(childId) == $ax.constants.LAYER_TYPE) { - $ax.visibility.applyWidgetContainer(childId, true).css(cssChange); - _popContainer(childId, false); - } else { - var childObj = $jobj(childId); - // if ($ax.public.fn.isCompoundVectorHtml(jobj[0])) { - // var grandChildren = jobj[0].children; - // //while (grandChildren.length > 0 && grandChildren[0].id.indexOf('container') >= 0) grandChildren = grandChildren[0].children; - // for (var j = 0; j < grandChildren.length; j++) { - // var grandChildId = grandChildren[j].id; - // if (grandChildId.indexOf(childId + 'p') >= 0 || grandChildId.indexOf('_container') >= 0) $jobj(grandChildId).css(cssChange); - // } - //} else - - var allObjs = $addAll(childObj, childId); // Just include other objects for initial css. Fixed panels need to be dealt with separately. - allObjs.css(cssChange); - - var fixedInfo = containedFixed[childId]; - if(fixedInfo) { - delete containedFixed[childId]; - - childObj.css('position', 'fixed'); - var deltaX = $ax.getNumFromPx(childObj.css('left')) - fixedInfo.left; - var deltaY = $ax.getNumFromPx(childObj.css('top')) - fixedInfo.top; - - fixedInfo = fixedInfo.fixed; - if(fixedInfo.horizontal == 'left') childObj.css('left', fixedInfo.x + deltaX); - else if(fixedInfo.horizontal == 'center') { - childObj.css('left', '50%'); - childObj.css('margin-left', fixedInfo.x + deltaX); - } else { - childObj.css('left', 'auto'); - childObj.css('right', fixedInfo.x - deltaX); - } - - if(fixedInfo.vertical == 'top') childObj.css('top', fixedInfo.y + deltaY); - else if(fixedInfo.vertical == 'middle') { - childObj.css('top', '50%'); - childObj.css('margin-top', fixedInfo.y + deltaY); - } else { - childObj.css('top', 'auto'); - childObj.css('bottom', fixedInfo.y - deltaY); - } - - $ax.dynamicPanelManager.updatePanelPercentWidth(childId); - $ax.dynamicPanelManager.updatePanelContentPercentWidth(childId); - - } - } - } - } - container.remove(); - trapScroll(); - }; - - var _trapScrollLoc = function(id) { - var locs = {}; - var states = $jobj(id).find('.panel_state'); - for(var i = 0; i < states.length; i++) { - var state = $(states[i]); - locs[state.attr('id')] = { x: state.scrollLeft(), y: state.scrollTop() }; - } - return function() { - for(var key in locs) { - var state = $jobj(key); - state.scrollLeft(locs[key].x); - state.scrollTop(locs[key].y); - } - }; - } - - var _getCurrFocus = function () { - // Only care about focused a tags and inputs - var id = window.lastFocusedClickable && window.lastFocusedClickable.id; - - if(!id) return id; - var jobj = $(window.lastFocusedClickable); - return jobj.is('a') || jobj.is('input') ? id : ''; - } - - var _setCurrFocus = function(id) { - if(id) { - // This is really just needed for IE, so if this causes issues on other browsers, try adding that check here - var trap = $ax.event.blockEvent($ax.repeater.removeSuffixFromElementId(id), 'OnFocus'); - window.setTimeout(function () { - $jobj(id).focus(); - trap(); - }, 0); - } - } - - //use this to save & restore DP's scroll position when show/hide - //key => dp's id (not state's id, because it seems we can change state while hiding) - //value => first state's id & scroll position - //we only need to store one scroll position for one DP, and remove the key after shown. - var DPStateAndScroll = {} - var _tryResumeScrollForDP = function (dpId, deleteId) { - var scrollObj = DPStateAndScroll[dpId]; - if(scrollObj) { - var shownState = document.getElementById(scrollObj.shownId); - if(scrollObj.left) shownState.scrollLeft = scrollObj.left; - if(scrollObj.top) shownState.scrollTop = scrollObj.top; - if(deleteId) delete DPStateAndScroll[dpId]; - } - }; -// var _makeContainer = function (containerId, rect, isFullWidth, isFlip, offset, containerExists) { - var _makeContainer = function (containerId, width, height, isFullWidth, isFlip, offset, containerExists) { - if(containerExists) var container = $jobj(containerId); - else { - container = $('<div></div>'); - container.attr('id', containerId); - } - var css = { - position: 'absolute', - width: width, - height: height, - display: 'flex' - }; - - if(!containerExists) { - // If container exists, may be busy updating location. Will init and update it correctly. - css.top = offset.top; - css.left = offset.left; - } - - - if(isFlip) { - css.perspective = '800px'; - css.webkitPerspective = "800px"; - css.mozPerspective = "800px"; - //adding this to make Edge happy - css['transform-style'] = 'preserve-3d'; - } else css.overflow = 'hidden'; - - //perspective on container will give us 3d effect when flip - //if(!isFlip) css.overflow = 'hidden'; - - // Rect should be a jquery not axquery obj - //_getFixedCss(css, rect.$ ? rect.$() : rect, fixedInfo, isFullWidth); - - container.css(css); - return container; - }; - - var CONTAINER_SUFFIX = _visibility.CONTAINER_SUFFIX = '_container'; - var CONTAINER_INNER = CONTAINER_SUFFIX + '_inner'; - _visibility.getWidgetFromContainer = function(id) { - var containerIndex = id.indexOf(CONTAINER_SUFFIX); - if(containerIndex == -1) return id; - return id.substr(0, containerIndex) + id.substr(containerIndex + CONTAINER_SUFFIX.length); - }; - - // Apply container to widget id if necessary. - // returnJobj: True if you want the jquery object rather than id returned - // skipCheck: True if you want the query returned reguardless of container existing - // checkInner: True if inner container should be checked - _visibility.applyWidgetContainer = function (id, returnJobj, skipCheck, checkInner) { - // If container exists, just return (return query if requested) - if(id.indexOf(CONTAINER_SUFFIX) != -1) return returnJobj ? $jobj(id) : id; - - // Get desired id, and return it if query is not desired - var containerId = $ax.repeater.applySuffixToElementId(id, checkInner ? CONTAINER_INNER : CONTAINER_SUFFIX); - if(!returnJobj) return containerId; - - // If skipping check or container exists, just return innermost container requested - var container = $jobj(containerId); - if(skipCheck || container.length) return container; - // If inner container was not checked, then no more to check, return query for widget - if(!checkInner) return $jobj(id); - - // If inner container was checked, check for regular container still - container = $jobj($ax.repeater.applySuffixToElementId(id, CONTAINER_SUFFIX)); - return container.length ? container : $jobj(id); - }; - - _visibility.isContainer = function(id) { - return id.indexOf(CONTAINER_SUFFIX) != -1; - }; - - _visibility.getRealChildren = function(query) { - while(query.length && $(query[0]).attr('id').indexOf(CONTAINER_SUFFIX) != -1) query = query.children(); - return query; - }; - - //var _getFixedCss = function(css, rect, fixedInfo, isFullWidth) { - // // todo: **mas** make sure this is ok - // if(fixedInfo.fixed) { - // css.position = 'fixed'; - - // if(fixedInfo.horizontal == 'left') css.left = fixedInfo.x; - // else if(fixedInfo.horizontal == 'center') { - // css.left = isFullWidth ? '0px' : '50%'; - // css['margin-left'] = fixedInfo.x; - // } else if(fixedInfo.horizontal == 'right') { - // css.left = 'auto'; - // css.right = fixedInfo.x; - // } - - // if(fixedInfo.vertical == 'top') css.top = fixedInfo.y; - // else if(fixedInfo.vertical == 'middle') { - // css.top = '50%'; - // css['margin-top'] = fixedInfo.y; - // } else if(fixedInfo.vertical == 'bottom') { - // css.top = 'auto'; - // css.bottom = fixedInfo.y; - // } - // } else { - // css.left = Number(rect.css('left').replace('px', '')) || 0; - // css.top = Number(rect.css('top').replace('px', '')) || 0; - // } - //}; - - var _slideStateOut = function (container, stateId, options, onComplete, jobj) { - var directionOut = options.direction; - var axObject = $ax('#' + container.attr('id')); - var width = axObject.width(); - var height = axObject.height(); - - _blockSetMoveIds = true; - - if(directionOut == "right") { - $ax.move.MoveWidget(stateId, width, 0, options, false, onComplete, false, jobj, true); - } else if(directionOut == "left") { - $ax.move.MoveWidget(stateId, -width, 0, options, false, onComplete, false, jobj, true); - } else if(directionOut == "up") { - $ax.move.MoveWidget(stateId, 0, -height, options, false, onComplete, false, jobj, true); - } else if(directionOut == "down") { - $ax.move.MoveWidget(stateId, 0, height, options, false, onComplete, false, jobj, true); - } - - _blockSetMoveIds = false; - }; - - var _slideStateIn = function (id, stateId, options, container, makePanelVisible, onComplete, jobj, preserveScroll) { - var directionIn = options.direction; - var axObject = $ax('#' +container.attr('id')); - var width = axObject.width(); - var height = axObject.height(); - - if (makePanelVisible) $ax.visibility.SetIdVisible(id, true); - for (i = 0; i < jobj.length; i++) $ax.visibility.SetVisible(jobj[i], true); - - for(var i = 0; i < jobj.length; i++) { - var child = $(jobj[i]); - var oldTop = $ax.getNumFromPx(fixAuto(child, 'top')); - var oldLeft = $ax.getNumFromPx(fixAuto(child, 'left')); - if (directionIn == "right") { - child.css('left', oldLeft - width + 'px'); - } else if(directionIn == "left") { - child.css('left', oldLeft + width + 'px'); - } else if(directionIn == "up") { - child.css('top', oldTop + height + 'px'); - } else if(directionIn == "down") { - child.css('top', oldTop - height + 'px'); - } - } - - if(preserveScroll) _tryResumeScrollForDP(id); - - _blockSetMoveIds = true; - - if(directionIn == "right") { - $ax.move.MoveWidget(stateId, width, 0, options, false, onComplete, false, jobj, true); - } else if(directionIn == "left") { - $ax.move.MoveWidget(stateId, -width, 0, options, false, onComplete, false, jobj, true); - } else if(directionIn == "up") { - $ax.move.MoveWidget(stateId, 0, -height, options, false, onComplete, false, jobj, true); - } else if(directionIn == "down") { - $ax.move.MoveWidget(stateId, 0, height, options, false, onComplete, false, jobj, true); - } - - _blockSetMoveIds = false; - }; - - $ax.visibility.GetPanelStateId = function(dpId, index) { - var itemNum = $ax.repeater.getItemIdFromElementId(dpId); - var panelStateId = $ax.repeater.getScriptIdFromElementId(dpId) + '_state' + index; - return $ax.repeater.createElementId(panelStateId, itemNum); - }; - - $ax.visibility.GetPanelStateCount = function(id) { - return $ax.visibility.getRealChildren($jobj(id).children()).filter("[id*='_state']").length; - }; - - var _bringPanelStateToFront = function (dpId, stateId, oldStateId, oldInFront) { - var panel = $jobj(dpId); - var frontId = oldInFront ? oldStateId : stateId; - if(containerCount[dpId]) { - frontId = $ax.visibility.applyWidgetContainer(frontId); - panel = $ax.visibility.applyWidgetContainer(dpId, true, false, true); - } - $jobj(frontId).appendTo(panel); - //when bring a panel to front, it will be focused, and the previous front panel should fire blur event if it's lastFocusedClickableSelector - //ie(currently 11) and firefox(currently 34) doesn't fire blur event, this is the hack to fire it manually - if((IE || FIREFOX) && window.lastFocusedClickable && $ax.event.getFocusableWidgetOrChildId(window.lastFocusedControl) == window.lastFocusedClickable.id) { - // Only need to do this if the currently focused widget is in the panel state that is being hidden. - if($jobj(oldStateId).find('#' + window.lastFocusedClickable.id.split('_')[0]).length) $(window.lastFocusedClickable).triggerHandler('blur'); - } - }; - - var _limboIds = _visibility.limboIds = {}; - // limboId's is a dictionary of id->true, essentially a set. - var _addLimboAndHiddenIds = $ax.visibility.addLimboAndHiddenIds = function(newLimboIds, newHiddenIds, query, skipRepeater) { - var limboedByMaster = {}; - for(var key in newLimboIds) { - if (!$ax.public.fn.IsReferenceDiagramObject($ax.getObjectFromElementId(key).type)) continue; - var ids = $ax.model.idsInRdoToHideOrLimbo(key); - for(var i = 0; i < ids.length; i++) limboedByMaster[ids[i]] = true; - } - - var hiddenByMaster = {}; - for(key in newHiddenIds) { - if (!$ax.public.fn.IsReferenceDiagramObject($ax.getObjectFromElementId(key).type)) continue; - ids = $ax.model.idsInRdoToHideOrLimbo(key); - for(i = 0; i < ids.length; i++) hiddenByMaster[ids[i]] = true; - } - - // Extend with children of rdos - newLimboIds = $.extend(newLimboIds, limboedByMaster); - newHiddenIds = $.extend(newHiddenIds, hiddenByMaster); - - // something is only visible if it's not hidden and limboed - query.each(function(diagramObject, elementId) { - // Rdos already handled, contained widgets are limboed by the parent, and sub menus should be ignored - if(diagramObject.isContained || $ax.public.fn.IsReferenceDiagramObject(diagramObject.type) || $ax.public.fn.IsTableCell(diagramObject.type) || $jobj(elementId).hasClass('sub_menu')) return; - if(diagramObject.type == 'table' && $jobj(elementId).parent().hasClass('ax_menu')) return; - if(skipRepeater) { - // Any item in a repeater should return - if($ax.getParentRepeaterFromElementIdExcludeSelf(elementId)) return; - } - - var scriptId = $ax.repeater.getScriptIdFromElementId(elementId); - var shouldBeVisible = Boolean(!newLimboIds[scriptId] && !newHiddenIds[scriptId]); - var isVisible = Boolean(_isIdVisible(elementId)); - if(shouldBeVisible != isVisible) { - _setWidgetVisibility(elementId, { value: shouldBeVisible, noContainer: true }); - } - }); - - _limboIds = _visibility.limboIds = $.extend(_limboIds, newLimboIds); - - }; - - var _clearLimboAndHidden = $ax.visibility.clearLimboAndHidden = function(ids) { - _limboIds = _visibility.limboIds = {}; - }; - - $ax.visibility.clearLimboAndHiddenIds = function(ids) { - for(var i = 0; i < ids.length; i++) { - var scriptId = $ax.repeater.getScriptIdFromElementId(ids[i]); - delete _limboIds[scriptId]; - } - }; - - $ax.visibility.resetLimboAndHiddenToDefaults = function (query) { - if(!query) query = $ax('*'); - _clearLimboAndHidden(); - _addLimboAndHiddenIds(_defaultLimbo, _defaultHidden, query); - }; - - $ax.visibility.isScriptIdLimbo = function(scriptId) { - if(_limboIds[scriptId]) return true; - - var repeater = $ax.getParentRepeaterFromScriptId(scriptId); - if(!repeater) return false; - - var itemId = $ax.getItemIdsForRepeater(repeater)[0]; - return _limboIds[$ax.repeater.createElementId(scriptId, itemId)]; - } - - $ax.visibility.isElementIdLimboOrInLimboContainer = function (elementId) { - var parent = document.getElementById(elementId); - while(parent) { - var scriptId = $ax.repeater.getScriptIdFromElementId($(parent).attr('id')); - if(_limboIds[scriptId]) return true; - parent = parent.parentElement; - } - return false; - } - - var _blockSetMoveIds = false; - var _movedIds = _visibility.movedIds = {}; - var _resizedIds = _visibility.resizedIds = {}; - var _rotatedIds = _visibility.rotatedIds = {}; - - $ax.visibility.getMovedLocation = function(scriptId) { - return _movedIds[scriptId]; - - //var repeater = $ax.getParentRepeaterFromScriptId(scriptId); - //if (!repeater) return false; - - //var itemId = $ax.getItemIdsForRepeater(repeater)[0]; - //return _movedIds[$ax.repeater.createElementId(scriptId, itemId)]; - }; - - $ax.visibility.setMovedLocation = function (scriptId, left, top) { - if ($jobj(scriptId).css('position') == 'fixed') return; - _movedIds[scriptId] = { left: left, top: top }; - }; - - $ax.visibility.moveMovedLocation = function (scriptId, deltaLeft, deltaTop) { - if(_blockSetMoveIds) return false; - - var offsetLocation = $ax('#' + scriptId).offsetLocation(); - $ax.visibility.setMovedLocation(scriptId, offsetLocation.x + deltaLeft, offsetLocation.y + deltaTop); - - if($ax.getTypeFromElementId(scriptId) == $ax.constants.LAYER_TYPE) { - var childIds = $ax('#' + scriptId).getChildren()[0].children; - for (var i = 0; i < childIds.length; i++) { - $ax.visibility.moveMovedLocation(childIds[i], deltaLeft, deltaTop); - } - } - }; - - $ax.visibility.getResizedSize = function(scriptId) { - return _resizedIds[scriptId]; - - //var repeater = $ax.getParentRepeaterFromScriptId(scriptId); - //if (!repeater) return false; - - //var itemId = $ax.getItemIdsForRepeater(repeater)[0]; - //return _resizedIds[$ax.repeater.createElementId(scriptId, itemId)]; - }; - - $ax.visibility.setResizedSize = function(scriptId, width, height) { - _resizedIds[scriptId] = { width: width, height: height }; - }; - - $ax.visibility.getRotatedAngle = function (scriptId) { - return _rotatedIds[scriptId]; - }; - - $ax.visibility.setRotatedAngle = function (scriptId, rotation) { - _rotatedIds[scriptId] = rotation; - }; - - $ax.visibility.clearMovedAndResized = function () { - _movedIds = _visibility.movedIds = {}; - _resizedIds = _visibility.resizedIds = {}; - _rotatedIds = _visibility.rotatedIds = {}; - }; - - $ax.visibility.clearMovedAndResizedIds = function (elementIds) { - for (var i = 0; i < elementIds.length; i++) { - var id = elementIds[i]; - delete _movedIds[id]; - delete _resizedIds[id]; - delete _rotatedIds[id]; - } - }; - - $ax.visibility.initialize = function() { - // initialize initial visible states - $('.' + HIDDEN_CLASS).each(function (index, diagramObject) { - _defaultHidden[$ax.repeater.getScriptIdFromElementId(diagramObject.id)] = true; - }); - - $('.' + UNPLACED_CLASS).each(function (index, diagramObject) { - _defaultLimbo[$ax.repeater.getScriptIdFromElementId(diagramObject.id)] = true; - }); - - _addLimboAndHiddenIds(_defaultLimbo, _defaultHidden, $ax('*'), true); - }; - - _visibility.initRepeater = function(repeaterId) { - var html = $('<div></div>'); - html.append($jobj(repeaterId + '_script').html()); - - html.find('.' + HIDDEN_CLASS).each(function (index, element) { - _defaultHidden[$ax.repeater.getScriptIdFromElementId(element.id)] = true; - }); - - html.find('.' + UNPLACED_CLASS).each(function (index, element) { - _defaultLimbo[$ax.repeater.getScriptIdFromElementId(element.id)] = true; - }); - } - - var HIDDEN_CLASS = _visibility.HIDDEN_CLASS = 'ax_default_hidden'; - var UNPLACED_CLASS = _visibility.UNPLACED_CLASS = 'ax_default_unplaced'; - -}); \ No newline at end of file diff --git a/web/main/static/resources/scripts/base.js b/web/main/static/resources/scripts/base.js index c906600..c625c0f 100644 --- a/web/main/static/resources/scripts/base.js +++ b/web/main/static/resources/scripts/base.js @@ -37,11 +37,57 @@ function set_select_data(select_ele_id,datas){ //设定选项选中状态 function set_select_selct(select_ele_id,option_str){ + let bfind = false; const select_Ele = document.getElementById(select_ele_id); for(let i=0;i< select_Ele.options.length;i++){ if(select_Ele.options[i].value === option_str){ select_Ele.options[i].selected = true; + bfind = true; break; } } -} \ No newline at end of file + return bfind; +} + +//将输入框内容转换为单精度型,若转换失败则返回0 -- 若需要整型,parseInt +function getInputValueAsFloat(id) { + var value = document.getElementById(id).value; + return value ? parseFloat(value) : 0; +} + +//正则匹配IP是否合法 return true,false +function isValidIP(ip) { + const ipRegex = /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/; + return ipRegex.test(ip); +} + +//post提交JSON数据 +function postJson(url,data){ + +} + +//post提交From数据 -- 返回数据是JSON +function postFrom(url,data){ + fetch(url, { + method: 'POST', + body: data, + }) + .then(response => response.json()) + .then(data => { + const istatus = data.status; + alert(data.msg); + if(istatus == 1 ){ + fetchModelData(); + $('#updateMM').modal('hide'); + } + }) + .catch(error => { + console.error('Error:', error); + alert('升级失败,请重试。'); + btn.disabled = false; + }); +} + +//get请求数据 +function getDATA(url){ +} diff --git a/web/main/static/resources/scripts/channel_manager.js b/web/main/static/resources/scripts/channel_manager.js index ee5f572..0459a03 100644 --- a/web/main/static/resources/scripts/channel_manager.js +++ b/web/main/static/resources/scripts/channel_manager.js @@ -20,28 +20,28 @@ let check_area = 0; let draw_status = false; //是否是绘制状态,处于绘制状态才能开始绘制 let b_img = false; //有没有加载图片成功,如果没有初始化的时候就不绘制线条了。 let points = []; - +//布防计划 document.addEventListener('DOMContentLoaded', function () { - fetchChannelData(); //初始化页面元素数据 + fetchChannelData(); //初始化通道管理页面元素数据 document.getElementById('searchButton').addEventListener('click', function () { performSearch(); }); - //新增通道 + //新增通道模块--保存按钮 document.getElementById('saveButton').addEventListener('click', function () { addChannel(1); }); - //修改通道 + //修改通道模块--保存按钮 document.getElementById('saveButton_cc').addEventListener('click', function () { addChannel(2); }); - //算法配置 + //算法配置模块--取消按钮 document.getElementById('cancelButton_mx').addEventListener('click', function () { close_mx_model(); }); - //保存算法配置 + //保存算法配置--保存按钮 document.getElementById('saveButton_mx').addEventListener('click', function () { save_mx_model(); }); @@ -57,25 +57,28 @@ function addChannel(itype) { let cName; let Rtsp; let cid; + const spinnerOverlay = document.getElementById("spinnerOverlay"); + let saveButton = null; + let CNameInput = null; + let RTSPInput = null; + if(itype ==1){ - const saveButton = document.getElementById('saveButton'); - const CNameInput = document.getElementById('CNameInput'); - const RTSPInput = document.getElementById('RTSPInput'); + saveButton = document.getElementById('saveButton'); + CNameInput = document.getElementById('CNameInput'); + RTSPInput = document.getElementById('RTSPInput'); area = document.getElementById('areaSelect_M').value; - cName = CNameInput.value.trim(); - Rtsp = RTSPInput.value.trim(); cid = -1 } else if(itype ==2){ - const saveButton = document.getElementById('saveButton_cc'); - const CNameInput = document.getElementById('CNameInput_cc'); - const RTSPInput = document.getElementById('RTSPInput_cc'); + saveButton = document.getElementById('saveButton_cc'); + CNameInput = document.getElementById('CNameInput_cc'); + RTSPInput = document.getElementById('RTSPInput_cc'); area = document.getElementById('areaSelect_CC').value; - cName = CNameInput.value.trim(); - Rtsp = RTSPInput.value.trim(); cid = currentEditingRow.cells[0].innerText; } - + console.log("点击了保存按钮"); + cName = CNameInput.value.trim(); + Rtsp = RTSPInput.value.trim(); if(area === "请选择"){ alert('请选择所属区域'); } @@ -85,6 +88,8 @@ function addChannel(itype) { //发送视频链接接口 const url = '/api/channel/add'; const data = {"area":area,"cName":cName,"Rtsp":Rtsp,"cid":cid}; + // 显示 Spinners + spinnerOverlay.style.display = "flex"; // 发送 POST 请求 fetch(url, { method: 'POST', // 指定请求方法为 POST @@ -96,27 +101,19 @@ function addChannel(itype) { .then(response => response.json()) // 将响应解析为 JSON .then(data => { const istatus = data.status; - if(istatus === 0){ - alert(data.msg); // 使用 Modal 显示消息 - // 启用保存按钮 - saveButton.disabled = false; - return; - } - else{ - // 启用保存按钮 - saveButton.disabled = false; + saveButton.disabled = false; + alert(data.msg); // 使用 Modal 显示消息 + if(istatus == 1){ //刷新列表 fetchChannelData(); if(itype ==1){ //添加通道成功 $('#channelModal').modal('hide'); - alert("添加通道成功!"); // 使用 Modal 显示消息 } else if(itype==2){ //修改通道成功 currentEditingRow = null; $('#ChangeC').modal('hide'); - alert("修改通道成功!"); // 使用 Modal 显示消息 } } }) @@ -125,6 +122,10 @@ function addChannel(itype) { // 启用保存按钮 saveButton.disabled = false; return; + }) + .finally(()=>{ + // 隐藏 Spinners + spinnerOverlay.style.display = "none"; }); } else { alert('通道名称和RTSP地址不能为空'); @@ -132,12 +133,22 @@ function addChannel(itype) { } } -async function fetchChannelData() { //刷新通道数据 +//初始化通道管理页面元素数据 +async function fetchChannelData() { //获取通道相关信息(/api/channel/list),刷新通道表格控件数据 try { const response = await fetch(apiEndpoint); channelData = await response.json(); channelData_bak = channelData; - renderTable(); //读取通道list接口,刷新表格 + + url = "/api/channel/area/list" + area_response = await fetch(url); + areaDatas = await area_response.json(); + areaData = ["请选择"]; //清空下 + areaDatas.forEach((area) => { + areaData.push(area.area_name) + }); + + renderTable(); //刷新表格 renderPagination(); //刷新分页元素 renderAreaOptions(); //所属区域下来框 } catch (error) { @@ -145,6 +156,41 @@ async function fetchChannelData() { //刷新通道数据 } } +//刷新表单页面数据 +function renderTable() { + const tableBody = document.getElementById('table-body'); + tableBody.innerHTML = ''; + + const start = (currentPage - 1) * rowsPerPage; + const end = start + rowsPerPage; + const pageData = channelData.slice(start, end); + const surplus_count = rowsPerPage - pageData.length; + + pageData.forEach((channel) => { +// if(area_name!==channel.area_name){ //这里要求区域名称一样的要在一起 +// area_name = channel.area_name; +// areaData.push(area_name); +// } + const row = document.createElement('tr'); + row.innerHTML = ` + <td>${channel.ID}</td> + <td>${channel.area_name}</td> + <td>${channel.channel_name}</td> + <td>${channel.ulr}</td> + <td>${channel.model_name}</td> + <td> + <button class="btn btn-primary btn-sm modify-btn">修改</button> + <button class="btn btn-secondary btn-sm algorithm-btn">算法</button> + <button class="btn btn-danger btn-sm delete-btn">删除</button> + </td> + `; + tableBody.appendChild(row); + row.querySelector('.modify-btn').addEventListener('click', () => modifyChannel(row)); + row.querySelector('.algorithm-btn').addEventListener('click', () => configureAlgorithm(row)); + row.querySelector('.delete-btn').addEventListener('click', () => deleteChannel(row)); + }); +} + //关键字查询数据 async function performSearch() { try { @@ -186,42 +232,7 @@ async function performSearch() { } } -//刷新表单页面数据 -function renderTable() { - const tableBody = document.getElementById('table-body'); - tableBody.innerHTML = ''; - - const start = (currentPage - 1) * rowsPerPage; - const end = start + rowsPerPage; - const pageData = channelData.slice(start, end); - const surplus_count = rowsPerPage - pageData.length; - let area_name = ""; - pageData.forEach((channel) => { - if(area_name!==channel.area_name){ //这里要求区域名称一样的要在一起 - area_name = channel.area_name; - areaData.push(area_name); - } - const row = document.createElement('tr'); - row.innerHTML = ` - <td>${channel.ID}</td> - <td>${channel.area_name}</td> - <td>${channel.channel_name}</td> - <td>${channel.ulr}</td> - <td>${channel.model_name}</td> - <td> - <button class="btn btn-primary btn-sm modify-btn">修改</button> - <button class="btn btn-secondary btn-sm algorithm-btn">算法</button> - <button class="btn btn-danger btn-sm delete-btn">删除</button> - </td> - `; - tableBody.appendChild(row); - row.querySelector('.modify-btn').addEventListener('click', () => modifyChannel(row)); - row.querySelector('.algorithm-btn').addEventListener('click', () => configureAlgorithm(row)); - row.querySelector('.delete-btn').addEventListener('click', () => deleteChannel(row)); - }); -} - -//修改通道信息 +//点击修改按钮,显示修改通道信息模块 --只是显示 function modifyChannel(row) { // const cid = row.cells[0].innerText; const areaName = row.cells[1].innerText; @@ -245,7 +256,7 @@ function modifyChannel(row) { $('#ChangeC').modal('show'); } -//算法配置 -- 点击算法按钮 +//点击算法按钮,显示算法配置模块 --只是显示 function configureAlgorithm(row) { //获取当前行信息 currentEditingRow = row; @@ -258,8 +269,8 @@ function configureAlgorithm(row) { b_img = false; document.getElementById('but_hzqy').textContent = "绘制区域"; //开始初始化算法管理模块 - show_channel_img(cid); //显示一帧图片 -- 获取不到图片就是黑画面 - show_channel_model_schedule(cid); //显示结构化数据 + show_channel_img(cid); //获取并显示一帧图片 -- 获取不到图片就是黑画面 + show_channel_model_schedule(cid); //获取并显示结构化数据 //显示窗口 $('#MX_M').modal('show'); } @@ -334,14 +345,21 @@ function handleRadioClick(event) { console.log('Selected Radio:', selectedRadio.id); // 根据选中的单选按钮执行相应操作 if (selectedRadio.id === 'qjjc') { - console.log("points.length",points.length); - // 处理全画面生效的逻辑 - if(points.length>0){ - if (!confirm('已经绘制了检测区域,确认要切换到全画面生效吗?')) { - document.getElementById('zdjc').checked = true; + if(draw_status){ + alert("请先结束绘制后,再切换检测方案!"); + document.getElementById('zdjc').checked = true; + } + else{ + // 处理全画面生效的逻辑 + if(points.length>0){ + if (!confirm('切换到全画面生效,将清除已绘制的区域信息,是否切换?')) { + document.getElementById('zdjc').checked = true; + }else{ + points = []; + } } } - console.log('全画面生效'); + //console.log('全画面生效'); } else if (selectedRadio.id === 'zdjc') { // 处理指定区域的逻辑 console.log('指定区域'); @@ -359,13 +377,47 @@ canvas.addEventListener('click', (event) => { const x = (event.clientX - rect.left) * scaleX; const y = (event.clientY - rect.top) * scaleY; - points.push({ x, y }); + console.log(points); //绘制线条 drawLines(); } }); -//初始化读取该视频通道与算法配置的相关信息 --- 这里用GET会更加贴切一些 +// 绘制区域,各点连接 +function drawLines() { + if(b_img){ + // 清除前台画布 + ctx.clearRect(0, 0, canvas.width, canvas.height); + // 将背景画布的内容复制到前台画布上 + ctx.drawImage(backgroundCanvas, 0, 0, canvas.width, canvas.height); + + // 绘制点和线 + ctx.strokeStyle = 'red'; + ctx.lineWidth = 2; + + if (points.length > 0) { + ctx.beginPath(); + ctx.moveTo(points[0].x, points[0].y); + + for (let i = 1; i < points.length; i++) { + ctx.lineTo(points[i].x, points[i].y); + } + + // 连接最后一个点到起点 + ctx.lineTo(points[0].x, points[0].y); + ctx.stroke(); + } + + points.forEach(point => { + ctx.beginPath(); + ctx.arc(point.x, point.y, 5, 0, Math.PI * 2); + ctx.fillStyle = 'red'; + ctx.fill(); + }); + } +} + +//获取并显示该通道相关算法的结构化数据 --- 这里用GET会更加贴切一些 function show_channel_model_schedule(cid){ //发送视频链接接口 const url = '/api/channel/C2M'; @@ -380,9 +432,9 @@ function show_channel_model_schedule(cid){ }) .then(response => response.json()) // 将响应解析为 JSON .then(data => { - const m_datas = data.m_datas; - const c2m_data = data.c2m_data; - const schedule = data.schedule; + const m_datas = data.m_datas; //算法清单 + const c2m_data = data.c2m_data; //该通道管理算法的相关数据,会有空的情况 + const schedule = data.schedule; //布防计划 //console.log("m_datas--",m_datas); //console.log("c2m_data--",c2m_data); //console.log("schedule--",schedule); @@ -412,13 +464,12 @@ function show_channel_model_schedule(cid){ drawLines(); } } - console.log("m_polygon",m_polygon); //阈值 document.getElementById('zxyz').value = c2m_data[0].conf_thres document.getElementById('iouyz').value = c2m_data[0].iou_thres } - + //布防计划 const days = ['一', '二', '三', '四', '五', '六','日']; const num_days=['0','1','2','3','4','5','6'] days.forEach((day, dayIndex) => { @@ -473,40 +524,6 @@ function parseCoordStr(str) { }); } -// 绘制区域,各点连接 -function drawLines() { - if(b_img){ - // 清除前台画布 - ctx.clearRect(0, 0, canvas.width, canvas.height); - // 将背景画布的内容复制到前台画布上 - ctx.drawImage(backgroundCanvas, 0, 0, canvas.width, canvas.height); - - // 绘制点和线 - ctx.strokeStyle = 'red'; - ctx.lineWidth = 2; - - if (points.length > 0) { - ctx.beginPath(); - ctx.moveTo(points[0].x, points[0].y); - - for (let i = 1; i < points.length; i++) { - ctx.lineTo(points[i].x, points[i].y); - } - - // 连接最后一个点到起点 - ctx.lineTo(points[0].x, points[0].y); - ctx.stroke(); - } - - points.forEach(point => { - ctx.beginPath(); - ctx.arc(point.x, point.y, 5, 0, Math.PI * 2); - ctx.fillStyle = 'red'; - ctx.fill(); - }); - } -} - //关闭算法配置窗口 function close_mx_model(){ if (confirm('确定退出窗口吗?未保存的修改将丢失!')) { @@ -516,13 +533,122 @@ function close_mx_model(){ //保存算法配置窗口数据 function save_mx_model(){ - //? - currentEditingRow =null; + let model_name; //算法名称 + let check_area; //检测区域标识 0-全局,1-指定范围 + let polygon_str; //具体的检测区域 + let conf_thres; //置信阈值 + let iou_thres; //iou阈值 + let schedule; //布防计划 + const saveButton = document.getElementById('saveButton_mx'); + saveButton.disabled = true; //不可点击状态 + //配置算法 + model_name = document.getElementById("model_select").value; + //检测区域 + if(document.getElementById('zdjc').checked){ + check_area = 1; + console.log("points--",points); + if (points.length > 0){ + const formattedArray = points.map(point => `(${point.x},${point.y})`); + polygon_str = `[${formattedArray.join(',')}]`; + }else{ + polygon_str = ""; + } + + }else{ + check_area = 0; + polygon_str = ""; + } + //置信阈值和IOU阈值 + conf_thres = getInputValueAsFloat('zxyz'); + iou_thres = getInputValueAsFloat('iouyz'); + //验证数据 + if(model_name !== "请选择"){ + console.log(model_name); + if(conf_thres <= 0 || conf_thres>=1 || iou_thres <= 0 || iou_thres>=1){ + alert("阈值的有效范围是大于0,小于1;请输入正确的阈值(默认可0.5)。"); + saveButton.disabled = false; //不可点击状态 + return; + } + } + //布防计划 + // 定义一个对象来存储数据 + const scheduleData = { + '0': Array(24).fill(0), + '1': Array(24).fill(0), + '2': Array(24).fill(0), + '3': Array(24).fill(0), + '4': Array(24).fill(0), + '5': Array(24).fill(0), + '6': Array(24).fill(0) + }; + // 遍历 tbody 的每一行 + [...tbody.children].forEach((row, dayIndex) => { + // 获取当前行的所有单元格 + const cells = row.getElementsByTagName('td'); + + // 遍历每一个单元格 + for (let hour = 0; hour < cells.length; hour++) { + // 检查单元格的 class 是否包含 'blocked' + if (cells[hour].classList.contains('blocked')) { + // 将对应的 scheduleData 位置设置为 1 + scheduleData[dayIndex][hour] = 1; + } else { + // 将对应的 scheduleData 位置设置为 0 + scheduleData[dayIndex][hour] = 0; + } + } + }); + // 将 scheduleData 对象转换为 JSON 字符串 + const scheduleData_json = JSON.stringify(scheduleData); + //提交到服务器 +// console.log("model_name--",model_name); +// console.log("check_area--",check_area); +// console.log("polygon_str--",polygon_str); +// console.log("iou_thres--",iou_thres); +// console.log("conf_thres--",conf_thres); +// console.log("schedule-- ",scheduleData_json); + cid = currentEditingRow.cells[0].innerText; + const url = '/api/channel/chanegeC2M'; + const data = {"model_name":model_name,"check_area":check_area,"polygon_str":polygon_str,"iou_thres":iou_thres, + "conf_thres":conf_thres,"schedule":scheduleData_json,"cid":cid}; + // 发送 POST 请求 + fetch(url, { + method: 'POST', // 指定请求方法为 POST + headers: { + 'Content-Type': 'application/json' // 设置请求头,告诉服务器请求体的数据类型为 JSON + }, + body: JSON.stringify(data) // 将 JavaScript 对象转换为 JSON 字符串 + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + const istatus = data.status; + if(istatus === 0){ + alert(data.msg); // 使用 Modal 显示消息 + // 启用保存按钮 + saveButton.disabled = false; + return; + } + else{ + // 启用保存按钮 + saveButton.disabled = false; + //刷新列表 + fetchChannelData(); + //$('#MX_M').modal('hide'); + alert("修改成功!"); + } + }) + .catch((error) => { + alert(`Error: ${error.message}`); + // 启用保存按钮 + saveButton.disabled = false; + return; + }); + } //删除通道 function deleteChannel(row) { - if (confirm('确定删除此区域吗?')) { + if (confirm('确定删除此通道吗?')) { cid = row.cells[0].innerText; //发送视频链接接口 const url = '/api/channel/del'; @@ -540,13 +666,9 @@ function deleteChannel(row) { const istatus = data.status; if(istatus === 0){ alert(data.msg); // 使用 Modal 显示消息 - // 启用保存按钮 - saveButton.disabled = false; return; } else{ - // 启用保存按钮 - saveButton.disabled = false; //刷新列表 row.remove(); alert("删除通道成功!"); @@ -554,8 +676,6 @@ function deleteChannel(row) { }) .catch((error) => { alert(`Error: ${error.message}`); // 使用 Modal 显示错误信息 - // 启用保存按钮 - saveButton.disabled = false; return; }); @@ -587,6 +707,11 @@ function renderAreaOptions() { const areaSelect = document.getElementById('areaSelect'); const areaSelect_M = document.getElementById('areaSelect_M') const areaSelect_CC = document.getElementById('areaSelect_CC') + //先清空 + areaSelect.innerHTML = ''; + areaSelect_M.innerHTML = ''; + areaSelect_CC.innerHTML = ''; + //再添加 areaData.forEach(option => { const optionElement = document.createElement('option'); optionElement.textContent = option; diff --git a/web/main/static/resources/scripts/model_manager.js b/web/main/static/resources/scripts/model_manager.js new file mode 100644 index 0000000..ec0b9fa --- /dev/null +++ b/web/main/static/resources/scripts/model_manager.js @@ -0,0 +1,303 @@ +let currentPage = 1; +const rowsPerPage = 10; +let modelData = []; +let modelData_bak = []; //用于关键字检索 +let currentEditingRow = null; + + + +//页面加载初始化 +document.addEventListener('DOMContentLoaded', function () { + fetchModelData(); //初始化通道管理页面元素数据 + //新增算法模态框---保存按钮 + document.getElementById('saveButton_model').addEventListener('click',function () { + addModel(); + }); + + //配置算法模态框--保存按钮 + document.getElementById('saveButton_config_model').addEventListener('click',function () { + post_configureModel(); + }); + + //升级算法模态框--保存按钮 + document.getElementById('saveButton_upmodel').addEventListener('click',function () { + post_modifyModel(); + }); + + //查询按钮 + document.getElementById('searchMButton').addEventListener('click',function () { + searchModel(); + }); +}); + +//获取算法列表数据,并更新页面 +async function fetchModelData() { + try{ + let response = await fetch('/api/model/list'); + if (!response.ok) { + throw new Error('Network response was not ok'); + } + modelData = await response.json(); + modelData_bak = modelData; + currentPage = 1; // 重置当前页为第一页 + renderTable(); //刷新表格 + renderPagination(); + }catch (error) { + console.error('Error fetching model data:', error); + } +} + +//刷新表单页面数据 +function renderTable() { + const tableBody = document.getElementById('table-body-model'); + tableBody.innerHTML = ''; //清空 + + const start = (currentPage - 1) * rowsPerPage; + const end = start + rowsPerPage; + const pageData = modelData.slice(start, end); + const surplus_count = rowsPerPage - pageData.length; + + + pageData.forEach((model) => { + const row = document.createElement('tr'); + row.innerHTML = ` + <td>${model.ID}</td> + <td>${model.name}</td> + <td>${model.version}</td> + <td>${model.duration_time}</td> + <td>${model.proportion}</td> + <td> + <button class="btn btn-primary btn-sm modify-btn">升级</button> + <button class="btn btn-secondary btn-sm algorithm-btn">配置</button> + <button class="btn btn-danger btn-sm delete-btn">删除</button> + </td> + `; + tableBody.appendChild(row); + row.querySelector('.modify-btn').addEventListener('click', () => modifyModel(row)); + row.querySelector('.algorithm-btn').addEventListener('click', () => configureModel(row)); + row.querySelector('.delete-btn').addEventListener('click', () => deleteModel(row)); + }); +} + +//刷新分页标签 +function renderPagination() { + const pagination = document.getElementById('pagination-model'); + pagination.innerHTML = ''; + + const totalPages = Math.ceil(modelData.length / rowsPerPage); + for (let i = 1; i <= totalPages; i++) { + const pageItem = document.createElement('li'); + pageItem.className = 'page-item' + (i === currentPage ? ' active' : ''); + pageItem.innerHTML = `<a class="page-link" href="#">${i}</a>`; + pageItem.addEventListener('click', (event) => { + event.preventDefault(); + currentPage = i; + renderTable(); + renderPagination(); + }); + pagination.appendChild(pageItem); + } +} + +//显示升级算法模态框 +function modifyModel(row){ + currentEditingRow = row; + model_name = row.cells[1].innerText; + version_name = row.cells[2].innerText; + + document.getElementById('update_mname_label').innerText = `算法名称: ${model_name}`; + document.getElementById('update_mversion_label').innerText = `当前版本: ${version_name}`; + $('#updateMM').modal('show'); +} + +//升级算法模态框--点击保存按钮 +function post_modifyModel(){ + mid = currentEditingRow.cells[0].innerText; + const btn = document.getElementById('saveButton_upmodel'); + const fileInput = document.getElementById('updateModelFile'); + const file = fileInput.files[0]; + if(file){ + btn.disabled = true; //不可点击 + const formData = new FormData(); + formData.append('file', file); + formData.append('mid', mid); + + fetch('/api/model/upgrade', { + method: 'POST', + body: formData, + }) + .then(response => response.json()) + .then(data => { + const istatus = data.status; + alert(data.msg); + btn.disabled = false; + if(istatus == 1 ){ + fetchModelData(); + $('#updateMM').modal('hide'); + } + }) + .catch(error => { + console.error('Error:', error); + alert('升级失败,请重试。'); + btn.disabled = false; + }); + } + else{ + alert('请选择升级包进行上传。'); + btn.disabled = false; + } +} + +//显示配置算法模态框 +function configureModel(row){ + currentEditingRow = row; + model_name = row.cells[1].innerText; + duration_time = row.cells[3].innerText; + proportion = row.cells[4].innerText; + //设置模态框控件遍历 + document.getElementById('config_mname_label').innerText = `算法名称: ${model_name}`; + document.getElementById('duration_timeInput').value = duration_time; + document.getElementById('proportionInput').value = proportion; + $('#configMM').modal('show'); +} + +//配置算法模态框--点击保存按钮 +function post_configureModel(){ + mid = currentEditingRow.cells[0].innerText; + duration_time = parseInt(document.getElementById('duration_timeInput').value); + proportion = parseFloat(document.getElementById('proportionInput').value); + if(isNaN(duration_time) || isNaN(proportion) ){ + alert("请输入数字!"); + return; + } + if(proportion<=0 || proportion>=1){ + alert("占比阈值需要大于0,且小于1"); + return; + } + //提交数据 + const url = '/api/model/changecnf'; + const data = {"mid":mid,"duration_time":duration_time,"proportion":proportion}; + // 发送 POST 请求 + fetch(url, { + method: 'POST', // 指定请求方法为 POST + headers: { + 'Content-Type': 'application/json' // 设置请求头,告诉服务器请求体的数据类型为 JSON + }, + body: JSON.stringify(data) // 将 JavaScript 对象转换为 JSON 字符串 + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + const istatus = data.status; + if(istatus === 0){ + alert(data.msg); + return; + } + else{ + //刷新列表 + fetchModelData(); + alert(data.msg); + $('#configMM').modal('hide'); + } + }) + .catch((error) => { + alert(`Error: ${error.message}`); + return; + }); +} + +//删除算法记录 +function deleteModel(row){ + if (confirm('确定删除此算法吗?')) { + mid = row.cells[0].innerText; + const url = '/api/model/del'; + const data = {"mid":mid}; + // 发送 POST 请求 + fetch(url, { + method: 'POST', // 指定请求方法为 POST + headers: { + 'Content-Type': 'application/json' // 设置请求头,告诉服务器请求体的数据类型为 JSON + }, + body: JSON.stringify(data) // 将 JavaScript 对象转换为 JSON 字符串 + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + const istatus = data.status; + if(istatus === 0){ + alert(data.msg); + return; + } + else{ + //刷新列表 + row.remove(); + alert("删除算法成功!"); + } + }) + .catch((error) => { + alert(`Error: ${error.message}`); + return; + }); + + } +} + +//新增算法--保存按钮 +function addModel(){ + const btn = document.getElementById('saveButton_model'); + const fileInput = document.getElementById('uploadModelFile'); + const file = fileInput.files[0]; + const mName = document.getElementById('MNameInput').value; + + if (file && mName) { + btn.disabled = true; //不可点击 + const formData = new FormData(); + formData.append('file', file); + formData.append('mName', mName); + + fetch('/api/model/add', { + method: 'POST', + body: formData, + }) + .then(response => response.json()) + .then(data => { + const istatus = data.status; + alert(data.msg); + btn.disabled = false; + if(istatus == 1 ){ + fetchModelData(); + $('#addMM').modal('hide'); + } + }) + .catch(error => { + console.error('Error:', error); + alert('上传失败,请重试。'); + btn.disabled = false; + }); + } else { + alert('请填写算法名称并选择一个升级包进行上传。'); + btn.disabled = false; + } +} + +//关键字检索 +function searchModel(){ + try { + const modelName = document.getElementById('modelNameInput').value; + if(modelName===""){ + modelData = modelData_bak; + } + else{ + modelData = []; + modelData_bak.forEach((model) => { + if(model.name.includes(modelName)){ + modelData.push(model); + } + }); + } + // 渲染表格和分页控件 + currentPage = 1; // 重置当前页为第一页 + renderTable(); + renderPagination(); + } catch (error) { + console.error('Error performing search:', error); + } +} \ No newline at end of file diff --git a/web/main/static/resources/scripts/player/axplayer.js b/web/main/static/resources/scripts/player/axplayer.js deleted file mode 100644 index 9b7ad43..0000000 --- a/web/main/static/resources/scripts/player/axplayer.js +++ /dev/null @@ -1,2631 +0,0 @@ -var PLUGIN_VAR_NAME = 'g'; -var FOOTNOTES_VAR_NAME = 'fn'; -var ADAPTIVE_VIEW_VAR_NAME = 'view'; -var SCALE_VAR_NAME = 'sc'; -var DIM_VAR_NAME = 'dm'; -var ROT_VAR_NAME = 'r'; -var CLOUD_VAR_NAME = 'cl'; -var TRACE_VAR_NAME = 'tr'; -var RP_VERSION = 9; -var lastLeftPanelWidth = 220; -var lastRightPanelWidth = 290; -var lastLeftPanelWidthDefault = 220; -var lastRightPanelWidthDefault = 290; -var toolBarOnly = true; - -// isolate scope -(function () { - - if (!window.$axure) window.$axure = function () { }; - if (typeof console == 'undefined') console = { - log: function () { } - }; - if (window._axUtils) $axure.utils = _axUtils; - - setUpController(); - - var getHashStringVar = $axure.player.getHashStringVar = function (query) { - var qstring = self.location.href.split("#"); - if (qstring.length < 2) return ""; - return GetParameter(qstring, query); - } - - var isCloud = $axure.player.isCloud = getHashStringVar(CLOUD_VAR_NAME); - if (isCloud) { - $("#topPanel").css('display', 'none'); - }else { - $("#topPanel").css('display', ''); - } - - $axure.loadDocument = function (document) { - $axure.document = document; - - var configuration = $axure.document.configuration; - var _settings = {}; - _settings.projectId = configuration.prototypeId; - _settings.projectName = configuration.projectName; - _settings.isAxshare = configuration.isAxshare; - _settings.isExpo = configuration.isExpo == null ? false : configuration.isExpo; - _settings.loadSitemap = configuration.loadSitemap; - _settings.loadFeedbackPlugin = configuration.loadFeedbackPlugin; - var cHash = getHashStringVar(SITEMAP_COLLAPSE_VAR_NAME); - _settings.startCollapsed = cHash == SITEMAP_COLLAPSE_VALUE; - if (cHash == SITEMAP_CLOSE_VALUE) closePlayer(); - var gHash = getHashStringVar(PLUGIN_VAR_NAME); - _settings.startPluginGid = gHash; - - $axure.player.settings = _settings; - - var additionalJs = $axure.document.additionalJs; - if (additionalJs != null) { - var total = additionalJs.length; - if (total > 0) $.holdReady(true); - $.each(additionalJs, function (index, value) { - var script = window.document.createElement("script"); - script.type = "text/javascript"; - script.src = value; - script.async = false; - script.onload = script.onreadystatechange = function (e) { - if (!script.readyState || /loaded|complete/.test(script.readyState)) { - script.onload = script.onreadystatechange = null; - script = undefined; - } - if (--total == 0) $.holdReady(false); - } - window.document.head.appendChild(script); - }); - } - - var additionalCss = $axure.document.additionalCss; - if(additionalCss != null) { - $.each(additionalCss, function(index, value) { - var style = window.document.createElement('link'); - style.type = "text/css"; - style.rel = "stylesheet"; - style.href = value; - window.document.head.appendChild(style); - }); - } - - if(_settings.isExpo && configuration.isMobile) { - initializeDeviceFrame(); - } - - // Pseudo-indicator that the document has been loaded - $axure.document.isLoaded = true; - }; - - $(window).bind('load', function () { - if ((CHROME && BROWSER_VERSION < 64) || // First 2018 release - (SAFARI && BROWSER_VERSION < 602) || // Minor version 10 - (FIREFOX && BROWSER_VERSION < 57) || // Support Quantum - ($axure.browser.isEdge && BROWSER_VERSION < 15) || // 15 for mobile devices (else could go 16, possibly 17) - (!$axure.browser.isEdge && IE)) { - if (!QQ && !UC) appendOutOfDateNotification(); - } - - if (CHROME_5_LOCAL && !$('body').attr('pluginDetected')) { - window.location = 'resources/chrome/chrome.html'; - } - - if (FIREFOX && BROWSER_VERSION >= 68 && document.location.href.indexOf('file://') >= 0) { //detecting firefox and local - window.location = 'resources/chrome/firefox.html'; - } - }); - - $(window).on('hashchange', function() { - window.location.reload(); - }); - - function appendOutOfDateNotification() { - var toAppend = ''; - toAppend += '<div id="browserOutOfDateNotification">'; - toAppend += ' <div style="font-size: 24px; text-align: center; color: #FFFFFF;">LOOKS LIKE YOUR BROWSER IS OUT OF DATE</div>'; - toAppend += ' <div style="font-size: 14px; text-align: center; color: #FFFFFF; margin-bottom: 16px;">This prototype may not look or function correctly until you update your browser</div>'; - toAppend += ' <div id="supportedBrowsersListContainer">'; - toAppend += ' <div class="browserContainer">'; - toAppend += ' <div class="browserName">Google Chrome</div><div class="browserSupportedVersion">v64 and later</div>'; - toAppend += ' </div>'; - toAppend += ' <div class="browserContainer">'; - toAppend += ' <div class="browserName">Mozilla Firefox</div><div class="browserSupportedVersion">v57 and later</div>'; - toAppend += ' </div>'; - toAppend += ' <div class="browserContainer">'; - toAppend += ' <div class="browserName">Microsoft Edge</div><div class="browserSupportedVersion">v15 and later</div>'; - toAppend += ' </div>'; - toAppend += ' <div class="browserContainer">'; - toAppend += ' <div class="browserName">Apple Safari</div><div class="browserSupportedVersion">v10 and later</div>'; - toAppend += ' </div>'; - toAppend += ' </div>'; - toAppend += ' <div id="browserOutOfDateNotificationButtons">' - if (!MOBILE_DEVICE) { - toAppend += ' <div style="margin-right: 36px"><a href="http://outdatedbrowser.com/en" id="updateBrowserButton">UPDATE BROWSER</a></div>'; - toAppend += ' <div style="flex: 0 1 45%;"><a id="continueToPrototypeButton">Continue viewing prototype anyway</a></div>'; - } else { - toAppend += ' <div style="width: 100%; text-align:center"><a id="continueToPrototypeButton">Continue viewing prototype anyway</a></div>'; - } - toAppend += ' </div>'; - toAppend += '</div>'; - - $('body').prepend(toAppend); - - $('#continueToPrototypeButton').on('click', function () { - var $message = $('#browserOutOfDateNotification'); - $message.children().hide(); - $message.css('padding-top', '0px'); - $message.animate({ 'height': '0px' }, { duration: 400, complete: function () { $message.hide(); } }); - }); - } - - $axure.page.bind('load.start', mainFrame_onload); - $axure.messageCenter.addMessageListener(messageCenter_message); - - var suppressPluginVarUpdate = false; - $(document).on('pluginShown', function (event, data) { - if (!suppressPluginVarUpdate) $axure.player.setVarInCurrentUrlHash(PLUGIN_VAR_NAME, data ? data : ''); - }); - - $(document).on('pluginCreated', function (event, data) { - if (!$axure.player.isMobileMode() && $axure.player.settings.startPluginGid.indexOf(data) > -1) { - suppressPluginVarUpdate = true; - $axure.player.showPlugin(data); - suppressPluginVarUpdate = false; - } - - if (data == '1') { - $('#interfaceControlFrame').animate({ opacity: 1 }, 200); - } - - if ($axure.player.settings.isExpo) { - // TODO: Do this only if expo is a mobile device - // TODO: Figure out better way to deal with this issue - $axure.messageCenter.postMessage('setDeviceMode', { device: false }); - $axure.messageCenter.postMessage('setDeviceMode', { device: true }); - //$axure.player.refreshViewPort(); - } - }); - - function initializeEvents() { - $('#interfaceControlFrameMinimizeContainer').on('click', collapse); - $('#interfaceControlFrameCloseButton').on('click', closePlayer); - $('#interfacePageNameContainer').on($axure.eventNames.mouseDownName, toggleSitemap); - $('#interfaceAdaptiveViewsContainer').on($axure.eventNames.mouseDownName, toggleAdaptiveViewsPopup); - $('#overflowMenuButton').on($axure.eventNames.mouseDownName, toggleOverflowMenuPopup); - - if (!MOBILE_DEVICE) { - $('#maximizePanel').mouseenter(function () { - $(this).addClass('maximizePanelOver'); - }); - $('#maximizePanel').mouseleave(function () { - if ($(this).hasClass('maximizePanelOver')) { - $(this).animate(isMobileMode() ? { - top: '-' + $('#maximizePanel').height() + 'px' - } : { - left: '-' + $('#maximizePanel').width() + 'px' - }, 300); - } - $(this).removeClass('maximizePanelOver'); - }); - $('#maximizePanelOver').mouseenter(function () { - $('#maximizePanel').animate(isMobileMode() ? { - top: '0px' - } : { - left: '0px' - }, 100); - }); - } - - $minimizeContainer = $('#interfaceControlFrameMinimizeContainer'); - $minimizeContainer.mouseenter(function () { $minimizeContainer.addClass('collapseHovered') }); - $minimizeContainer.mouseleave(function () { $minimizeContainer.removeClass('collapseHovered') }); - $maximizeContainer = $('#maximizePanelContainer'); - $maximizeContainer.mouseenter(function () { if(!MOBILE_DEVICE) $minimizeContainer.addClass('expandHovered') }); - $maximizeContainer.mouseleave(function () { if(!MOBILE_DEVICE) $minimizeContainer.removeClass('expandHovered') }); - - $('#maximizePanel').click(function () { - $(this).removeClass('maximizePanelOver'); - $('#maximizePanelContainer').hide(); - $axure.messageCenter.postMessage('expandFrame'); - }); - - $('#mHideSidebar').on($axure.eventNames.mouseDownName, function (e) { startM(e); }); - $('#lsplitbar').on($axure.eventNames.mouseDownName, startLeftSplit); - $('#rsplitbar').on($axure.eventNames.mouseDownName, startRightSplit); - - if ($axure.mobileSupport.mobile) { - var touchCount = 0; - var lastTouch = Date.now(); - $('#mainPanel').on('touchstart', - (function (e) { - var now = Date.now(); - if (now - lastTouch < 375) { - if (++touchCount === 3) { - if ($axure.player.isMobileMode() || MOBILE_DEVICE) expand(); - touchCount = 0; - e.preventDefault(); - }; - } else { - touchCount = 1; - } - lastTouch = now; - })); - } - - $(window).resize(function () { - $axure.player.resizeContent(); - }); - - $(window).on("orientationchange", function () { - // IOS often does not complete updating innerHeight and innerWidth - // until after calling orientation changed and resized window - // Also, cannot use $(window).height() call since iOS11 needs padding amount - if (IOS && isMobileMode()) setTimeout(function () { $axure.player.resizeContent(true); }, 250); - }); - - $('#mainPanel').scroll(function () { - repositionClippingBoundsScroll(); - }); - } - - function initializeMainFrame() { - var legacyQString = getQueryString("Page"); - if (legacyQString.length > 0) { - location.href = location.href.substring(0, location.href.indexOf("?")) + "#" + PAGE_URL_NAME + "=" + legacyQString; - return; - } - - var mainFrame = document.getElementById("mainFrame"); - //if it's local file on safari, test if we can access mainframe after its loaded - if (SAFARI && document.location.href.indexOf('file://') >= 0) { - $(mainFrame).on('load', function () { - var canAccess; - try { - var mainFrameWindow = mainFrame.contentWindow || mainFrame.contentDocument; - mainFrameWindow['safari_file_CORS'] = 'Y'; - canAccess = mainFrameWindow['safari_file_CORS'] === 'Y'; - } catch (err) { - canAccess = false; - } - - if (!canAccess) window.location = 'resources/chrome/safari.html'; - }); - } - - if($axure.player.settings != null && !$axure.player.settings.isExpo) { - const linkUrlWithVars = $axure.getLinkUrlWithVars(getInitialUrl()); - mainFrame.contentWindow.location.href = linkUrlWithVars; - } - } - - function initializeDeviceFrame() { - // TODO: Load device bezel and necessary overlays if applicable - // - Need to determine if device has a frame/overlay - // - Determine where to store said assets - // - Determine sizing, positioning, orientation, and styling for HTML containers - // - Verify that it stays consistent for every state (expo) - - var expo = $axure.expo; - var project = expo.project; - var device = project.Platform.Device; - - // in expo.ts, Web is 12 - if (device === 12) { - // Hide containers - $('#deviceFrameContainer').hide(); - $('#bezelOverlay').hide(); - - return; - } - - // map devices to their corresponding frame/bezel/overlays - } - var wasMobile = false; - var isMobileMode = $axure.player.isMobileMode = function () { return $axure.utils.isShareApp() || (MOBILE_DEVICE && $(window).width() < 420); } - var isMobileTextEntry = false; - - var isViewOverridden = $axure.player.isViewOverridden = function() { - return getHashStringVar(ADAPTIVE_VIEW_VAR_NAME).length > 0; - } - - function toggleSitemapMobileMode() { - var $container = $('#sitemapHost'); - if (!$container.length) return; - var $header = $container.find('.pluginNameHeader'); - var projectName = $axure.player.getProjectName(); - - if (isMobileMode()) { - $header.text('PROJECT PAGES'); - $container.addClass('mobileMode'); - $container.find('.sitemapPageName').addClass('mobileText'); - // Give sitemapHost left-margin so it does not collide with projectOptionsHost - if (MOBILE_DEVICE) $container.css('margin-left', '13px'); - } else { - $container.removeClass('mobileMode'); - $header.text(projectName ? projectName : 'Pages'); - $container.find('.sitemapPageName').removeClass('mobileText'); - if (MOBILE_DEVICE) $container.css('margin-left', ''); - } - } - - function togglePageNotesMobileMode() { - var $container = $('#pageNotesHost'); - if (!$container.length) return; - - if (isMobileMode()) { - $container.addClass('mobileMode'); - $('#pageNotesSectionHeader').text('PAGE NOTES'); - $('#widgetNotesSectionHeader').text('WIDGET NOTES'); - $container.find('.notesPageNameHeader').addClass('mobileSubHeader'); - $container.find('.pageNote').addClass('mobileText'); - $container.find('.emptyStateTitle').addClass('mobileSubHeader'); - $container.find('.emptyStateContent').addClass('mobileText'); - } else { - $container.removeClass('mobileMode'); - $('#pageNotesSectionHeader').text('Page Notes'); - $('#widgetNotesSectionHeader').text('Widget Notes'); - $container.find('.notesPageNameHeader').removeClass('mobileSubHeader'); - $container.find('.pageNote').removeClass('mobileText'); - $container.find('.emptyStateTitle').removeClass('mobileSubHeader'); - $container.find('.emptyStateContent').removeClass('mobileText'); - } - - } - - function toggleFeedbackMobileMode() { - var $container = $('#feedbackHost'); - if (!$container.length) return; - - if (isMobileMode()) { - $container.addClass('mobileMode'); - } else { - $container.removeClass('mobileMode'); - } - } - - $axure.player.updatePlugins = function updatePlugins() { - if (MOBILE_DEVICE && !$axure.utils.isShareApp()) { - var hostPanelPadding = isMobileMode() ? '8px 15px 0px 15px' : ''; - $('.rightPanel .leftPanel .mobileOnlyPanel').css('padding', hostPanelPadding); - } - - if (isMobileMode()) { - $('body').addClass('mobileMode'); - if ($('#debugHost').length) $('#debugHost').hide(); - if ($('#handoffHost').length) $('#handoffHost').hide(); - } else $('body').removeClass('mobileMode'); - - toggleSitemapMobileMode(); - togglePageNotesMobileMode(); - toggleFeedbackMobileMode(); - } - - // TODO: this is done for IOS and Android (check what can be done for Pixel, etc) - $axure.player.setIsMobileModeTextEntry = function (isTextEntry) { - isMobileTextEntry = isTextEntry; - if (IOS && isTextEntry) { - activateMobileTextEntry() - } else if (IOS) { - setTimeout(deactivateMobileTextEntry, 150); - } - } - - function deactivateMobileTextEntry() { - newHeight = window.innerHeight; - var newControlHeight = newHeight - (!$axure.utils.isShareApp() ? 140 : IOS ? 157 : 138); - - if (!$('.leftPanel').hasClass('popup')) { - $('.leftPanel').height(newControlHeight); - } - $('.rightPanel').height(newControlHeight); - $('.mobileOnlyPanel').height(newControlHeight); - $('#mobileControlFrameContainer').show(); - } - - function activateMobileTextEntry() { - $('#mobileControlFrameContainer').hide(); - - newHeight = window.innerHeight; - var newControlHeight = newHeight - (!$axure.utils.isShareApp() ? 140 : IOS ? 157 : 138); - newControlHeight = newControlHeight + (!$axure.utils.isShareApp() ? 61 : IOS ? 72 : 60); - - if (!$('.leftPanel').hasClass('popup')) { - $('.leftPanel').height(newControlHeight); - } - $('.rightPanel').height(newControlHeight); - $('.mobileOnlyPanel').height(newControlHeight); - } - - function setAdaptiveView() { - if (typeof noViewport == 'undefined') { - // Block during animation -- end of animation will call resizeContent once completed with isAnimating equal to false - if (!isViewOverridden() && !isAnimating) $axure.messageCenter.postMessage('setAdaptiveViewForSize', { 'width': $('#mainPanel').width(), 'height': $('#mainPanel').height() }); - //if (!isViewOverridden()) $axure.messageCenter.postMessage('setAdaptiveViewForSize', { 'width': $('#mainPanel').width(), 'height': $('#mainPanel').height() }); - $axure.player.refreshViewPort(); - if ($axure.player.updateAdaptiveViewHeader != null) $axure.player.updateAdaptiveViewHeader(); - } - } - - $axure.player.resizeContent = function (noViewport) { - var isMobile = isMobileMode(); - - if (wasMobile && !isMobile) { - $('#clippingBoundsScrollContainer').show(); - $('#outerContainer').prepend($('.leftPanel')); - $('#outerContainer').append($('.rightPanel')); - - $axure.player.updatePlugins(); - - $('#mHideSidebar').hide(); - $('#mobileBrowserControlFrame').hide(); - $('#nativeAppControlFrame').hide(); - - if ($('#topPanel').is(':visible')) { - $('#maximizePanelContainer').hide(); - $axure.player.restorePlugins(); - } else { - $('.leftPanel').hide(); - $('.rightPanel').hide(); - if (!MOBILE_DEVICE) $('#maximizePanelContainer').show(); - } - - $('.leftPanel').css({ 'top': '', 'left': '' }); - $('.rightPanel').css({ 'top': '', 'left': '' }); - - } else if (!wasMobile && isMobile) { - $('#clippingBoundsScrollContainer').hide(); - $axure.player.closePopup(); - - $('#lsplitbar').hide(); - $('#rsplitbar').hide(); - - $('.leftPanel').show(); - $('.rightPanel').show(); - - $axure.player.updatePlugins(); - $('#mHideSidebar').append($('.leftPanel')); - $('#mHideSidebar').append($('.rightPanel')); - if (MOBILE_DEVICE) $('#maximizePanelContainer').hide(); - - $axure.messageCenter.postMessage('collapseFrameOnLoad'); - } - - - var newHeight = 0; - var newWidth = 0; - if (IOS && $axure.utils.isShareApp()) { - // Hack for Iphone X - newHeight = iosInnerHeight(); - newWidth = $(window).width(); - } else { - // innerHeight includes padding for window -- needed in iOS 11 to have prototype stretch to bottom of screen (could put in -- if (iOS) -- block if needed) - //var newHeight = $(window).height() - ((!isMobile && $('#topPanel').is(':visible'))? $('#topPanel').height() : 0); - newHeight = window.innerHeight - ((!isMobile && $('#topPanel').is(':visible')) ? $('#topPanel').height() : 0); - newWidth = $(window).width(); - } - - $('#outerContainer').height(newHeight).width(newWidth); - $('#mainPanel').height(newHeight); - $('#clippingBounds').height(newHeight); - - if (isMobile) { - $('#mobileControlFrameContainer').height(newHeight); - $('#mobileControlFrameContainer').width(newWidth); - var newControlHeight = newHeight - (!MOBILE_DEVICE ? 112 : !$axure.utils.isShareApp() ? 140 : IOS ? 157 : 138); - // Screen resize is only way through browser to catch mobile device keyboard expand and collapse - if ($('#mHideSidebar').is(':visible') && !$('#mobileControlFrameContainer').is(':visible')) { - $('#mobileControlFrameContainer').delay(150).show(); - } else if (isMobileTextEntry) { - newControlHeight = newControlHeight + (!$axure.utils.isShareApp() ? 61 : IOS ? 72 : 60); - $('#mobileControlFrameContainer').hide(); - } - - if(!$('.leftPanel').hasClass('popup')) { - $('.leftPanel').height(newControlHeight); - } - $('.rightPanel').height(newControlHeight); - $('.mobileOnlyPanel').height(newControlHeight); - } else { - if (!$('.leftPanel').hasClass('popup')) { - $('.leftPanel').css('height',''); - } - $('.rightPanel').css('height', ''); - if ($('.rightPanel').is(':visible')) { - var lastRightPanelWidthDefaultSub = ($(window).width() - lastRightPanelWidthDefault || 0); - var rightPanelWidth = ($('.rightPanel').width() || 0); - var leftPanelPanelWidthSub = ($(window).width() - $('.leftPanel').width()) || 0; - - var newWidth = Math.min(lastRightPanelWidthDefaultSub, rightPanelWidth, leftPanelPanelWidthSub); - lastRightPanelWidth = Math.max(lastRightPanelWidthDefault, newWidth); - $('.rightPanel').width(lastRightPanelWidth ? lastRightPanelWidth : lastRightPanelWidthDefault); - $('#rsplitbar').css('left', $(window).width() - $('.rightPanel').width()); - } - if ($('.leftPanel').is(':visible')) { - var lastLeftPanelWidthSub = ($(window).width() - lastLeftPanelWidthDefault || 0); - var leftPanelWidth = ($('.leftPanel').width() || 0); - var rightPanelWidthSub = ($(window).width() - $('.rightPanel').width()) || 0; - - var newWidth = Math.min(lastLeftPanelWidthSub, leftPanelWidth, rightPanelWidthSub); - - lastLeftPanelWidth = Math.max(lastLeftPanelWidthDefault, newWidth); - $('.leftPanel').width(lastLeftPanelWidth ? lastLeftPanelWidth : lastLeftPanelWidthDefault); - $('#lsplitbar').css('left', $('.leftPanel').width() - 4); - } - } - - if (isMobile) { - var newControlWidth = newWidth - 80; - $('.leftPanel').css({ 'width': newControlWidth + 'px' }); - $('.rightPanel').css({ 'width': newControlWidth + 'px' }); - $('.mobileOnlyPanel').css({ 'width': newControlWidth + 'px' }); - adjustM('left'); - } - - updateClippingBoundsWidth(); - repositionClippingBoundsScroll(); - setAdaptiveView(); - - wasMobile = isMobile; - } - - function contentDocument_onload() { - (function setRepositionWhenReady() { - var $iframe = $('#mainPanel').find('iframe')[0]; - if ($($iframe.contentWindow.document.body).length === 0 || $iframe.contentWindow.document.URL === "about:blank") { - setTimeout(setRepositionWhenReady, 50); - } else { - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow.document); - $iframe.scroll(function () { - repositionClippingBoundsScroll(); - }); - } - })(); - } - - // This is the full width and height of the prototype (beyond the window width and height) - var determineIframeDimensions = function () { - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow); - - return { - width: $iframe.width(), - height: $iframe.height() - }; - }; - - // Position of this (upper left hand corner) should match the existingPinPanel position - var determineIframePosition = function () { - var dimensions = determineIframeDimensions(); - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow); - - var $body = $($iframe[0].document.body); - var bodyWidth = $body.offset().left !== 0 ? $body.width() : dimensions.width; - - if (FIREFOX) { - var left = $body[0].getBoundingClientRect().left; - bodyWidth = left !== 0 ? $body.width() : dimensions.width; - } - - return { - top: 0,// Math.max(0, (dimensions.height - $($iframe[0].document.body).height()) / 2), - left: Math.max(0, (dimensions.width - bodyWidth) / 2) - }; - }; - - // Return iframe scroll top and scroll left - var determineIframeScroll = function () { - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow); - - return { - scrollTop: $iframe.scrollTop(), - scrollLeft: $iframe.scrollLeft() - }; - }; - - function calculateClippingBoundsWidth(panelSize, isLeftPanel) { - var $leftPanel = $('.leftPanel:visible'); - var leftPanelOffset = (!isMobileMode() && $leftPanel.length > 0 && !$leftPanel.hasClass('popup')) ? $leftPanel.width() : 0; - - var $rightPanel = $('.rightPanel:visible'); - var rightPanelOffset = (!isMobileMode() && $rightPanel.length > 0) ? $rightPanel.width() : 0; - - // Replace current panel size with panel size after animation for expand or collapse completes - if (typeof panelSize !== 'undefined') { - if (isLeftPanel) leftPanelOffset = panelSize; - else rightPanelOffset = panelSize; - } - - return $(window).width() - rightPanelOffset - leftPanelOffset; - } - - var updateClippingBoundsWidth = $axure.player.updateClippingBoundsWidth = function () { - if ($('.leftPanel').is(':visible')) $('#clippingBounds').css('left', $('.leftPanel').width()); - else $('#clippingBounds').css('left', '0px'); - $('#clippingBounds').width(calculateClippingBoundsWidth()); - } - - var contentLeftOfOriginOffset = 0; - function calculateClippingBoundsScrollPosition() { - // Adjust for mainPanelContainer scaling (scale should be "none" for scaleVal == 0 or scaleVal == 1) - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow); - var selectedScale = $('.vpScaleOption').find('.selectedRadioButton'); - var scaleVal = $(selectedScale).parent().attr('val'); - - var dimStr = $('.currentAdaptiveView').attr('data-dim'); - var dim = dimStr ? dimStr.split('x') : { w: '0', h: '0' }; - var isDevice = dim[1] != '0' ? true : false; - // This line is necessary for right handling DEFAULT SCALE - // Because default scale relates to scale-to-fit item for device projects - if (scaleVal == '0' && isDevice) scaleVal = 2; - - var scale = $('#mainPanelContainer').css('transform');; - scale = (scale == "none") ? 1 : Number(scale.substring(scale.indexOf('(') + 1, scale.indexOf(','))); - - // Iframe and Main Panel Positioning - var iframeScroll = determineIframeScroll(); - var iframePos = determineIframePosition(); - var viewablePanelLeftMargin = parseInt($('#mainPanelContainer').css('margin-left')); - var viewablePanelTop = parseInt($('#mainPanelContainer').css('top')); - if (isNaN(viewablePanelTop)) viewablePanelTop = 0; - if (scaleVal == 2) { - // Scale to Fit (account for main panel container scale) -- needed for device mode in Scale to Fit - viewablePanelLeftMargin = ($('#mainPanel').width() - ($('#mainPanelContainer').width() * scale)) / 2 - viewablePanelTop = ($('#mainPanel').height() - ($('#mainPanelContainer').height() * scale)) / 2 - } - - // left and top positioning - var leftPos = viewablePanelLeftMargin + (iframePos.left - iframeScroll.scrollLeft) * scale; - var topPos = viewablePanelTop - iframeScroll.scrollTop * scale; - - // Special cases for Centered Page - var isCentered = $($iframe[0].document.body).css('position') == 'relative'; - if (isCentered && scaleVal == 1) leftPos = 0; - else if (isCentered && scaleVal == 2) leftPos = $('#mainPanelContainer').width() * scale / 2.0 - contentLeftOfOriginOffset; - - // Include clipFrameScroll offset in mainPanelContainer - topPos += (parseFloat($('#clipFrameScroll').css("top")) || 0) * scale; - - return { - left: leftPos, - top: topPos - } - } - - function repositionClippingBoundsScroll() { - if (!$axure.player.settings.isAxshare) return; - - (function repositionWhenReady() { - if ($($('#mainPanel').find('iframe')[0].contentWindow.document.body).length === 0) { - setTimeout(repositionWhenReady, 50); - } else { - var position = calculateClippingBoundsScrollPosition(); - - // Adding mainPanel scroll here, since it does not work well with calculating animation left position - position.left = position.left - $('#mainPanel').scrollLeft() - $('#clipFrameScroll').scrollLeft(); - position.top = position.top - $('#mainPanel').scrollTop() - $('#clipFrameScroll').scrollTop(); - - $('#clippingBoundsScrollContainer').css('left', position.left + 'px'); - $('#clippingBoundsScrollContainer').css('top', position.top + 'px'); - } - })(); - } - - function calculateScrollLeftWithOffset(offset, isLeftPanel) { - if (!$axure.player.settings.isAxshare) return; - if ($($('#mainPanel').find('iframe')[0].contentWindow.document.body).length === 0) return; - var scaleVal = $('.vpScaleOption').find('.selectedRadioButton').parent().attr('val'); - if (scaleVal == 2) return; - - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow); - var $body = $($iframe[0].document.body); - - var dimStr = $('.currentAdaptiveView').attr('data-dim'); - var hasFrame = (!dimStr ? false : dimStr.split('x')[1] != '0') && !$axure.player.noFrame; - var isCentered = $body.css('position') == 'relative'; //body position is always static while page is still loading (thus false, if called on intial load) - var isCollapsing = offset > 0; //offset is positive when collapsing since we are gaining offset more space for content viewing - - // Base case left positioning - var leftPos = calculateClippingBoundsScrollPosition().left; - - // If maintaining view options requires a left adjustment not equivalent to panel size (which has already being added in leftPos above) - var viewAdjustment = 0; - - // Mobile Frame adjustment - if (hasFrame) { - var viewablePanelLeftMargin = parseInt($('#mainPanelContainer').css('margin-left')); - var viewablePanelRightMargin = parseInt($('#mainPanelContainer').css('margin-right')); - - // Cases - // 0) Adaptive view frame doesn't fit in viewable bounds (viewablePanelLeftMargin is zero) -- use entire offset of panel (no adjustment needed) - // 1) Adaptive view frame fits in bounds -- then half of incoming panel will be split left and half right (offset / 2) - // 2) and 3) View Frame either fits in bounds before animation and no longer will after, or vice versa. Mix of previous two cases - if (isCollapsing) { - if (viewablePanelLeftMargin != 0) { - viewAdjustment = offset / 2; - } else if (-viewablePanelRightMargin < offset) { - viewAdjustment = ((offset + viewablePanelRightMargin) / 2); - } - } else if (viewablePanelLeftMargin != 0) { - viewAdjustment = Math.max(offset / 2, -viewablePanelLeftMargin) - } - } - - // Centered Page adjustment - if (isCentered) { - // Width of content not able to fit inside current viewable frame - var clippedContentWidth = $body.width() - calculateClippingBoundsWidth(Math.abs(offset), isLeftPanel); - - // Cases - // 0) Content never fits in bounds -- then entire offset of panel will move content left value (no adjustment needed as already handled) - // 1) Content fits in bounds -- then half of incoming panel offset will be split left and half right (offset / 2) - // 2) and 3) Content either fits in bounds before animation and no longer will after, or vice versa. Mix of previous two cases - if (clippedContentWidth <= 0) { - viewAdjustment = offset / 2; - } else if (isCollapsing && clippedContentWidth < offset) { - viewAdjustment = (offset - clippedContentWidth) / 2; - } else if (!isCollapsing && clippedContentWidth < -offset) { - viewAdjustment = (clippedContentWidth + offset) / 2; - } - } - - return leftPos + viewAdjustment; - } - - // Set to true when left panel or right panel are being expanded/collapsed - // returns to false when lsplitbar (switched to clippingBounds) finishes animation (thus panels will be fully expanded or retracted at this point) - var isAnimating = $axure.player.isAnimating = false; - - $axure.player.collapseToBar = function (context, hostId) { - lastLeftPanelWidth = $('.leftPanel').width(); - lastRightPanelWidth = $('.rightPanel').width(); - if (context === 'project' || context === 'all') { - - if(!isMobileMode()) { - isAnimating = true; - var newWidth = lastLeftPanelWidth != 0 ? lastLeftPanelWidth : lastLeftPanelWidthDefault; - var clippingWidth = calculateClippingBoundsWidth(0, true); - var newLeft = calculateScrollLeftWithOffset(newWidth, true); - - $('.leftPanel').animate({ 'margin-left': -newWidth + 'px' }, - { duration: 200, complete: function() { $('.leftPanel').width(0).hide().css({ 'margin-left': '' }); } }); - $('#lsplitbar').animate({ left: '-4px' }, - { duration: 200, complete: function() { $('#lsplitbar').hide(); } }); - - $('#clippingBounds').animate({ left: '', width: clippingWidth + 'px' }, { duration: 200 }); - $('#clippingBoundsScrollContainer').animate({ left: newLeft + 'px' }, - { duration: 200, complete: function () { - isAnimating = false; - $axure.player.resizeContent(); - $axure.player.pluginVisibleChanged(hostId, false); - }}); - } else { - $('.leftPanel').width(0); - $('#lsplitbar').hide(); - } - } - if (context === 'inspect' || context === 'all') { - if (!isMobileMode()) { - isAnimating = true; - var newWidth = lastRightPanelWidth != 0 ? lastRightPanelWidth : lastRightPanelWidthDefault; - var clippingWidth = calculateClippingBoundsWidth(0, false); - var newLeft = calculateScrollLeftWithOffset(newWidth, false); - - $('.rightPanel').animate({ 'margin-right': -newWidth + 'px' }, - { duration: 200, complete: function () { $('.rightPanel').width(0).hide().css({ 'margin-right': '' }); } }); - $('#rsplitbar').animate({ left: $(window).width() + 'px' }, - { duration: 200, complete: function () { $('#rsplitbar').hide(); } }); - - $('#clippingBounds').animate({ width: clippingWidth + 'px' }, { duration: 200 }); - $('#clippingBoundsScrollContainer').animate({ left: newLeft + 'px' }, - { duration: 200, complete: function () { - isAnimating = false; - $axure.player.resizeContent(); - $axure.player.pluginVisibleChanged(hostId, false); - }}); - } else { - $('.rightPanel').width(0); - $('#rsplitbar').hide(); - } - } - - $(window).resize(); - toolBarOnly = true; - } - - $axure.player.expandFromBar = function (hostId, context, isFinalPluginToRestore) { - - if (context === 'project') { - if ($('#lsplitbar').is(':visible')) return; - $('.leftPanel').removeClass('popup'); - if(!isMobileMode()) { - isAnimating = true; - var newWidth = (lastLeftPanelWidth ? lastLeftPanelWidth : lastLeftPanelWidthDefault); - var clippingWidth = calculateClippingBoundsWidth(newWidth, true); - var newLeft = calculateScrollLeftWithOffset(-newWidth, true); - - $('.leftPanel').width(newWidth); - $('.leftPanel').css('margin-left', -newWidth + 'px').show(); - $('.leftPanel').animate({ 'margin-left': '0px' }, { duration: 200, complete: function () { $('.leftPanel').css({ 'margin-left': '' }); } }); - - $('#lsplitbar').css('left', '-4px'); - $('#lsplitbar').show(); - $('#lsplitbar').animate({ left: newWidth - 4 + 'px' }, { duration: 200 }); - - $('#clippingBounds').animate({ left: newWidth + 'px', width: clippingWidth + 'px' }, { duration: 200 }); - $('#clippingBoundsScrollContainer').animate({ left: newLeft + 'px' }, - { duration: 200, complete: function () { - isAnimating = false; - $axure.player.resizeContent(); - if (isFinalPluginToRestore) $('#clippingBoundsScrollContainer').show(); - $axure.player.pluginVisibleChanged(hostId, true); - }}); - } - } else { - if ($('#rsplitbar').is(':visible')) { - // update width of rightPanel plugin - var newWidth = lastRightPanelWidth ? lastRightPanelWidth : lastRightPanelWidthDefault; - $('#' + hostId).width(newWidth); - $('#' + hostId).show(); - $axure.player.pluginVisibleChanged(hostId, true); - return; - } - if (!isMobileMode()) { - isAnimating = true; - var newWidth = lastRightPanelWidth ? lastRightPanelWidth : lastRightPanelWidthDefault; - var clippingWidth = calculateClippingBoundsWidth(newWidth, false); - var newLeft = calculateScrollLeftWithOffset(-newWidth, false); - - $('.rightPanel').width(newWidth); - $('.rightPanel').css('margin-right', -newWidth + 'px'); - $('#' + hostId).show(); - $('.rightPanel').animate({ 'margin-right': '0px' }, { duration: 200, complete: function () { $('.rightPanel').css({ 'margin-right': '' }); } }); - - $('#rsplitbar').css('left', $(window).width()); - $('#rsplitbar').show(); - $('#rsplitbar').animate({ left: $(window).width() - $('.rightPanel').width() + 'px' }, { duration: 200 }); - - $('#clippingBounds').animate({ width: clippingWidth + 'px' }, { duration: 200 }); - $('#clippingBoundsScrollContainer').animate({ left: newLeft + 'px' }, - { duration: 200, complete: function () { - isAnimating = false; - $axure.player.resizeContent(); - if (isFinalPluginToRestore) $('#clippingBoundsScrollContainer').show(); - $axure.player.pluginVisibleChanged(hostId, true); - }}); - } - } - $(window).resize(); - toolBarOnly = false; - - if (isMobileMode()) { - $('#mHideSidebar').show(); - $('#nativeAppControlFrame').show(); - } - } - - var suspendRefreshViewPort = $axure.player.suspendRefreshViewPort = false; - $axure.player.refreshViewPort = function () { - if (suspendRefreshViewPort) return; - - var dimStr = $('.currentAdaptiveView').attr('data-dim'); - var dim = dimStr ? dimStr.split('x') : { w: '0', h: '0' }; - var w = dim[0] != '0' ? dim[0] : ''; - var h = dim[1] != '0' ? dim[1] : ''; - - var scaleVal = $('.vpScaleOption').find('.selectedRadioButton').parent().attr('val'); - var selectedScaleValue = scaleVal; - $axure.player.noFrame = false; - if (h && scaleVal == 1) $axure.player.noFrame = true; - - $('#mainPanelContainer').attr({ - "data-scale-n": scaleVal, - "data-page-dimensions-type": h ? "device" : w ? "web" : "auto", - "data-scale-shift-x": null, - "data-scale-shift-y": null, - }); - - var clipToView = h && !$axure.player.noFrame; - var isDevice = h; - - var mainPanelWidth = $('#mainPanel').width(); - var mainPanelHeight = $('#mainPanel').height(); - - if (!w || !clipToView) w = mainPanelWidth; - if (!h || !clipToView) h = mainPanelHeight; - if (MOBILE_DEVICE && h > mainPanelHeight) h = mainPanelHeight; - if (MOBILE_DEVICE && w > mainPanelWidth) w = mainPanelWidth; - - if (clipToView) { - if (!MOBILE_DEVICE && scaleVal == '0') scaleVal = 2; - - w = Number(w); - h = Number(h); - - $('#mainFrame').width(w); - $('#clipFrameScroll').width(w); - $('#mainFrame').height(h); - $('#clipFrameScroll').height(h); - - var topPadding = MOBILE_DEVICE ? 0 : 10; - var leftPadding = 0; - var rightPadding = 0; - var bottomPadding = MOBILE_DEVICE ? 0 : 10; - - w = w + leftPadding + rightPadding; - h = h + topPadding + bottomPadding; - - var x = (mainPanelWidth - w) / 2; - var y = (mainPanelHeight - h) / 2 - 1; - - if (scaleVal != 2) { - x = Math.max(0, x); - y = Math.max(0, y); - } - - $('#mainPanelContainer').attr({ - "data-scale-shift-x": x, - "data-scale-shift-y": y, - }); - - $('#mainPanelContainer').css({ - 'margin': 'auto', - 'top': y + 'px', - 'left': (x < 0 ? x + 'px' : 'auto') - }); - - $('#clipFrameScroll').css({ - 'left': leftPadding + 'px', - 'top': topPadding + 'px' - }); - - $('#mainPanelContainer').width(w); - $('#mainPanelContainer').height(h); - } else { - $('#mainFrame').width('100%'); - $('#mainFrame').height(h); - - $('#clipFrameScroll').width('100%'); - $('#clipFrameScroll').height(h); - $('#clipFrameScroll').css({ 'left': '', 'top': '' }); - - $('#mainPanelContainer').width('100%'); - $('#mainPanelContainer').height(h); - $('#mainPanelContainer').css({ - 'left': '', - 'margin': '', - 'top': '' - }); - } - $axure.messageCenter.postMessage('setDeviceMode', { device: isDevice, width: w, scaleToWidth: (scaleVal == "1") }); - - $(".vpScaleOption").show(); - var prevScaleN = $('#mainPanelContainer').css('transform'); - prevScaleN = (prevScaleN == "none") ? 1 : Number(prevScaleN.substring(prevScaleN.indexOf('(') + 1, prevScaleN.indexOf(','))); - var newScaleN = 1; - - $('#mainPanelContainer').css({ - 'transform': '', - 'transform-origin': '' - }); - - var $leftPanel = $('.leftPanel:visible'); - var leftPanelOffset = (!isMobileMode() && $leftPanel.length > 0) ? $leftPanel.width() : 0; - var $rightPanel = $('.rightPanel:visible'); - var rightPanelOffset = (!isMobileMode() && $rightPanel.length > 0) ? $rightPanel.width() : 0; - - var vpScaleData = { - scale: scaleVal, - prevScaleN: prevScaleN, - viewportHeight: h, - viewportWidth: w, - panelWidthOffset: leftPanelOffset + rightPanelOffset, - clipToView: clipToView - }; - $axure.messageCenter.postMessage('getScale', vpScaleData); - $axure.messageCenter.postMessage('cloud_ScaleValueChanged', { - scale: selectedScaleValue, - }); - if (scaleVal == '0' && clipToView) $('#mainPanel').css('overflow', 'auto'); - else $('#mainPanel').css('overflow', ''); - } - - $axure.player.getProjectName = function getProjectName() { - if (typeof PREVIEW_INFO !== 'undefined') { - return PREVIEW_INFO.fileName; - } else if(typeof $axure.player.settings.projectName !== 'undefined') { - return $axure.player.settings.projectName; - } else return false; - } - - function initializeLogo() { - - if(typeof PREVIEW_INFO !== 'undefined') { - $('#previewNotice').show(); - } - - //if (typeof PREVIEW_INFO !== 'undefined') { - // $('#interfaceControlFrameLogoCaptionContainer').html(PREVIEW_INFO.fileName); - //} else if (typeof $axure.player.settings.projectName !== 'undefined') { - // $('#interfaceControlFrameLogoCaptionContainer').html($axure.player.settings.projectName); - //} else { - // $('#interfaceControlFrameLogoCaptionContainer').hide(); - //} - - //if ($axure.document.configuration.logoImagePath) { - // var image = new Image(); - // //image.onload = function () { - // // //$('#logoImage').css('max-width', this.width + 'px'); - // // $('#interfaceControlFrameContainer').css('margin-left', '-' + $('#logoImage').width() / 2 + 'px'); - // // //$axure.player.resizeContent(); - // //}; - // image.src = $axure.document.configuration.logoImagePath; - - // $('#interfaceControlFrameLogoImageContainer').html('<img id="logoImage" src="" />'); - // $('#logoImage').attr('src', $axure.document.configuration.logoImagePath);//.on('load', function () { $axure.player.resizeContent(); }); - //} else $('#interfaceControlFrameLogoImageContainer').hide(); - - //if ($axure.document.configuration.logoImageCaption) { - // $('#interfaceControlFrameLogoCaptionContainer').html($axure.document.configuration.logoImageCaption); - //} else $('#interfaceControlFrameLogoCaptionContainer').hide(); - - //if(!$('#interfaceControlFrameLogoImageContainer').is(':visible') && !$('#interfaceControlFrameLogoCaptionContainer').is(':visible')) { - // $('#interfaceControlFrameLogoContainer').hide(); - //} - } - - function initializePreview() { - if (typeof PREVIEW_INFO !== 'undefined') { - $('#separatorContainer').addClass('hasLeft'); - $('#overflowMadeWith').addClass('preview'); - - var callback = undefined; - $('#publishButton').click(function () { - $.ajax({ - type: 'GET', - url: 'publish', - data: {}, - success: function (response) { - if (callback) callback(response); - }, - error: function (response) { - if (callback) callback(response); - }, - dataType: 'jsonp' - }); - }); - } - } - - var userAcct = { - userId: '', - userName: '', - userEmail: '', - userProfileImg: '', - isUsingAxureAcct: false, - } - - var authCookieValue = null; - var userCookieValue = null; - var isSubInstance = false; - //var readOnlyMode = false; - //var readOnlyMessage = ''; - - // Watermark hints - // NOTE: The trailing characters serve to be a distinguishing element in case the user actually does use text similar to the hint. - var emailHint = "Email "; - var passHint = "Password "; - - var feedbackServiceUrl = (window.AXSHARE_HOST_SECURE_URL || 'https://share.axure.com') + '/issue'; - // Look at creating a new location to have GetShareStatus(FbEnabled replacement) and SafariAuth since they are more general calls that are not solely for feedback now - //var prototypeControlUrl = (window.AXSHARE_HOST_SECURE_URL || 'https://share.axure.com') + '/prototype'; - - // Checks if the browser is Safari 3.0+ - // https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser - function isSafari() { - // Safari 3.0+ "[object HTMLElementConstructor]" - var liveSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification)); - return liveSafari || SAFARI || (IOS && $axure.utils.isShareApp()); - }; - - var iosInnerHeight = (function () { - if (!navigator.userAgent.match(/iphone|ipod|ipad/i)) { - /** - * Avoids conditional logic in the implementation - * @return {number} - window's innerHeight measurement in pixels - */ - return function () { - return window.innerHeight; - }; - } - - // Store initial orientation - var axis = Math.abs(window.orientation); - // And hoist cached dimensions - var dims = { w: 0, h: 0 }; - - /** - * Creates an element with a height of 100vh since iOS accurately - * reports vp height (but not window.innerHeight). Then destroy it. - */ - var createRuler = function () { - var ruler = document.createElement('div'); - - ruler.style.position = 'fixed'; - ruler.style.height = '100vh'; - ruler.style.width = 0; - ruler.style.top = 0; - - document.documentElement.appendChild(ruler); - - // Set cache conscientious of device orientation - dims.w = axis === 90 ? ruler.offsetHeight : window.innerWidth; - dims.h = axis === 90 ? window.innerWidth : ruler.offsetHeight; - - // Clean up after ourselves - document.documentElement.removeChild(ruler); - ruler = null; - }; - - // Measure once - createRuler(); - - /** - * Returns window's cached innerHeight measurement - * based on viewport height and device orientation - * @return {number} - window's innerHeight measurement in pixels - */ - return function () { - if (Math.abs(window.orientation) !== 90) { - return dims.h; - } - - return dims.w; - }; - }()); - - function includeTokens(ajaxData, excludeUser) { - //If the authCookieValue is set (a password-protected local prototype), then send the - //token as well (because cookies don't always get sent to external domains) - if (authCookieValue) { - $.extend(ajaxData, { token: authCookieValue }); - } - if (!excludeUser && userCookieValue) { - $.extend(ajaxData, { utoken: userCookieValue }); - } - } - - function setUserLoggedInStatus(response, safariAuthResponseProfile) { - if (!response.success) { - userAcct.isUsingAxureAcct = false; - } else { - if (safariAuthResponseProfile) response = safariAuthResponseProfile; - userAcct.userId = response.userId; - if (safariAuthResponseProfile) - userAcct.userName = response.username == null || response.username.trim() === '' ? response.userEmail : response.username.trim(); - else - userAcct.userName = response.nickname == null || response.nickname.trim() === '' ? response.userEmail : response.nickname.trim(); - userAcct.userEmail = response.userEmail; - userAcct.userProfileImg = response.profileImageUrl; - userAcct.isUsingAxureAcct = true; - - if (response.authToken != null) { - $axshare.setAuthCookie(response.authToken); - userCookieValue = response.authToken; - } - } - - // If feedback is loaded, update feedback with new account information - if (typeof feedback !== 'undefined') feedback.updateUserAccountInfo(userAcct, authCookieValue, userCookieValue); - } - - // TODO: for on prem, we need to use an ajax call directly to share instead of accounts - // Verify authentication against axure accounts - $axure.player.axureAuth = function axureAuth(callback) { - if (window.$axshare != null) { - $axshare.auth(function (response) { - if (response.success) { - setUserLoggedInStatus(response); - } else { - if (isSafari()) { - var ajaxData = { - userId: userAcct.isUsingAxureAcct ? userAcct.userId : "" - }; - includeTokens(ajaxData); - - $.ajax({ - type: 'GET', - url: feedbackServiceUrl + '/safariAuth', - data: ajaxData, - success: function (response) { - if (!response.success) { - setUserLoggedInStatus(response); - } else { - setUserLoggedInStatus(response, response.data.profile[userAcct.userId]); - - if (callback != null) { - callback(response); - } - } - }, - dataType: 'jsonp' - }); - } else { - setUserLoggedInStatus(response); - } - } - - if (callback != null) { - callback(response); - } - - }); - } - } - - // TODO: for on prem, we need to use an ajax call directly to share instead of accounts - // Log into axure accounts - $axure.player.axureLogin = function axureLogin(email, password, success, failure, saml) { - if (window.$axshare != null) { - password = password === passHint ? "" : password; - $axshare.login(email, password, false, function (response) { - if (response.redirecturl !== "" && response.redirecturl != null) { - saml(response); - return; - } - - if (response.success && (response.verified || isSubInstance)) { - if (isSafari()) setUserLoggedInStatus(response); - $axure.player.axureAuth(success); - } else { - failure(response); - } - }, window.ON_PREM_LDAP_ENABLED); - } else { - failure(); - } - } - - function playerLogout() { - userAcct.isUsingAxureAcct = false; - userAcct.userId = ''; - userAcct.userProfileImg = ''; - - // If feedback is loaded, update feedback with new account information - if (typeof feedback !== 'undefined') feedback.updateUserAccountInfo(userAcct); - } - - $axure.player.logout = function (feedbackLogout) { - var completeLogout = playerLogout; - if (feedbackLogout) { - completeLogout = function () { - feedbackLogout(); - playerLogout(); - } - } - if (window.$axshare != null) { - $axshare.logout(completeLogout); - } else { - completeLogout(); - } - } - - /* - * TODO: Start of Login/Account Mgmt UI, which will need to be updated (currenly uses feedback9.css often) - */ - function buildAccountLoginPopup() { - return [ - '<div class="axClearMsgBubble_Player axureLoginBubble_Player">', - ' <div class="axureLoginBubbleContainer_Player">', - ' <span style="font-weight: bold; font-size: 10px;">Login into your Axure Cloud account</span>', - ' <input type="text" autocapitalize="none" name="email" class="axureEmail" style="margin-top: 7px;"/>', - ' <input name="password" autocapitalize="none" class="axurePassword" />', - ' <div class="feedbackGreenBtn_Player">LOG IN</div>', - ' <div class="errorMessage"></div>', - ' <div id="playerSignUpLink" style="text-align: right; margin-top: 5px; font-size: 10px;">', - ' <span>No account? <a class="axureSignUpLink" href="', window.AXSHARE_HOST_SECURE_URL, '" target="_blank">Sign Up</a></span>', - ' </div>', - ' </div>', - '</div>' - ].join(""); - } - - // Bind events to axure login speech bubble (watermark, login, errors, click outside) - function bindAxureLoginContainerEvent() { - var $container = $("#accountLoginContainer"); - $container.find('input[name="email"]').addClass("watermark").val(emailHint).focus(function () { - if ($(this).val() === emailHint) { - $(this).removeClass("watermark").val(""); - } - }).blur(function () { - if ($(this).val() === "") { - $(this).addClass("watermark").val(emailHint); - } - - $container.find('.errorMessage').text(''); - $container.find('.errorMessage').hide(); - }).keyup(function (event) { - if (event.keyCode == 13) { - $container.find('.feedbackGreenBtn').click(); - } - }); - $container.find('input[name="password"]').addClass("watermark").val(passHint).focus(function () { - if ($(this).val() === passHint) { - $(this).removeClass("watermark").val(""); - //$(this).removeClass("watermark").val("").attr("type", "password"); - - // Note: this might be an issue since jquery doesn't like it. Test in IE - $(this)[0].setAttribute('type', 'password'); - } - }).blur(function () { - if ($(this).val() === "") { - $(this).val(passHint).addClass("watermark"); - //$(this).val(passHint).addClass("watermark").removeAttr("type"); - - // Note: this might be an issue since jquery doesn't like it. Test in IE - $(this)[0].setAttribute('type', 'text'); - } - - $container.find('.errorMessage').text(''); - $container.find('.errorMessage').hide(); - }).keyup(function (event) { - if (event.keyCode == 13) { - $container.find('.feedbackGreenBtn_Player').click(); - } - }); - - // Login Submit Event - $container.find('.feedbackGreenBtn_Player').click(function (e) { - var email = $container.find('.axureEmail').val(); - var password = $container.find('.axurePassword').val(); - - $axure.player.axureLogin(email, password, function (response) { - // Success - // Clear out fields - $container.find('.axureEmail').val(emailHint).addClass("watermark"); - $container.find('.axurePassword').val(passHint).addClass("watermark"); - $container.find('.axurePassword')[0].setAttribute('type', 'text'); - - closePopup(); - }, function (response) { - // Failure - $container.find('.errorMessage').text(response != null && response.message ? response.message : "There was an error connecting to the server, please try again later."); - $container.find('.errorMessage').show(); - }, function (response) { - // SAML User - $container.find('.errorMessage').empty(); - $container.find('.errorMessage').append("Please <a class='refreshLink' style='text-decoration: underline;'>refresh</a> this page after logging in via your identity provider."); - $container.find('.errorMessage').show(); - - window.open(response.redirecturl, '_blank'); - - $container.find('.errorMessage').find('.refreshLink').click(function () { - location.reload(true); - }); - }); - }); - }; - - function initializeSignIn() { - if (typeof PREVIEW_INFO === 'undefined' && $axure.player.settings.isAxshare) { - (function finishInit() { - if (window.$axshare == null || $axshare.auth == null || $axshare.login == null) { - setTimeout(finishInit, 50); - } else { - // Call to set readOnlyMode, readOnlyMessage, and isSubinstance (readOnlyMode/Message currently only used for feedback9) - $.ajax({ - type: 'GET', - url: feedbackServiceUrl + '/GetShareStatus', - data: {}, - success: function (response) { - //readOnlyMode = response.readOnlyMode; - //readOnlyMessage = response.readOnlyMessage; - isSubInstance = response.isSubInstance; - if (isSubInstance) $('#accountLoginContainer').find("#playerSignUpLink").hide(); - - // For now, calling methods to set these values in feedback on start (could later make a general method to retrieve these values from player) - if (typeof feedback !== 'undefined') { - feedback.setReadOnlyModeAndMessage(response.readOnlyMode, response.readOnlyMessage); - feedback.setIsSubInstance(isSubInstance); - } - }, - dataType: 'jsonp' - }); - - // Login container - $("#accountLoginContainer").append(buildAccountLoginPopup()); - bindAxureLoginContainerEvent(); - - // Attempt to auth and acquire account information, then update top panel - $axure.player.axureAuth(); - } - })(); - } - } - - function overflowIsHidden(node) { - var style = getComputedStyle(node); - return style.overflow === 'hidden' || style.overflowX === 'hidden' || style.overflowY === 'hidden'; - } - - function findNearestScrollableParent(firstNode) { - var node = firstNode; - var scrollable = null; - while (!scrollable && node) { - if (node.scrollWidth > node.clientWidth || node.scrollHeight > node.clientHeight) { - if (!overflowIsHidden(node) || $(node).css('-webkit-overflow-scrolling') === 'touch') { - scrollable = node; - } - } - node = node.parentNode; - } - return scrollable; - } - - function getScrollOwner(target) { - var owner = findNearestScrollableParent(target); - if (!owner || owner === document.documentElement || owner === document.body || $(owner).parents('#topPanel').length || owner == document.getElementById('forwardSlash')) { - return null; - } - - return owner; - } - - function removeElasticScrollFromIframe() { - var $iframe = $($('#mainPanel').find('iframe')[0].contentWindow); - $iframe[0].document.body.addEventListener('touchmove', function (event) { - if (!getScrollOwner(event.target)) { - event.preventDefault(); - } - }, { passive: false }); - } - - $(document).ready(function () { - (function finishPlayerInit() { - if ($axure.player.settings.isAxshare) { - $axure.page.bind('load.start', contentDocument_onload); - if ($axure.player.settings.loadFeedbackPlugin) { - $axure.utils.loadJS('/Scripts/plugins/feedback/feedback9.js'); - - /******* DEBUG: Allows for debugging/viewing feedback9.js in browser inspect mode ******/ - //var hdr = document.createElement('script'); - //hdr.type = "text/javascript" - //hdr.src = '/Scripts/plugins/feedback/feedback9.js'; - //document.head.appendChild(hdr); - } - } - - initializeEvents(); - initializeMainFrame(); - - $('.leftPanel').width(0); - - $('#maximizePanelContainer').hide(); - - if ($axure.player.settings.startCollapsed) { - collapse(); - $('.leftPanel').width(0); - - var maxPanelWidth = $('#maximizePanel').width(); - setTimeout(function() { - $('#maximizePanel').animate({ - left:'-' + maxPanelWidth + 'px' - }, 300); - }, 2000); - } - - if (MOBILE_DEVICE) { - $('body').removeClass('hashover'); - - if (SAFARI) { - // Stop pinch zoom (stopping all gestures for now) - // Gesturestart is only supported in Safari - document.addEventListener("gesturestart", function (e) { - e.preventDefault(); - }); - } - - if (IOS) { - // Attempt at removing elastic scroll while in mobile menu - var touching = false; - var pageYStart = 0; - var pageYOffset = 0; - document.body.addEventListener('touchend', function (event) { - if (getScrollOwner(event.target)) { - touching = false; - } - }, { passive: false }); - - document.body.addEventListener('touchmove', function (event) { - var owner = getScrollOwner(event.target) - if (!owner) { - event.preventDefault(); - } else { - if ($(owner).scrollTop() == 0) { - if (touching) { - if (event.pageY >= pageYStart) { - event.preventDefault(); - } - } - } - if ($(owner).scrollTop() + $(owner).height() == owner.scrollHeight) { - if (touching) { - if (event.pageY <= pageYStart) { - event.preventDefault(); - } - } - } - } - }, { passive: false }); - - document.body.addEventListener('touchstart', function (event) { - var owner = getScrollOwner(event.target); - if (owner) { - if ($(owner).scrollTop() == 0) { - touching = true; - pageYStart = event.pageY; - pageYOffset = event.pageY; - } - if ($(owner).scrollTop() + $(owner).height() == owner.scrollHeight) { - touching = true; - pageYStart = event.pageY; - pageYOffset = event.pageY; - } - } - }, { passive: false }); - - removeElasticScrollFromIframe(); - - $('html').css('-webkit-tap-highlight-color', 'transparent'); - - // Stop iOS from automatically scaling parts of the mobile player - // Could stop automatic scaling on Ipads as well that we actually want, but for now, seems fine - $('body').css('-webkit-text-size-adjust', '100%'); - - window.addEventListener("orientationchange", function () { - var viewport = document.querySelector("meta[name=viewport]"); - //so iOS doesn't zoom when switching back to portrait - if (IOS) { - viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover'); - viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, viewport-fit=cover'); - } else { - viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0'); - viewport.setAttribute('content', 'width=device-width, initial-scale=1.0'); - } - $axure.player.resizeContent(); - }, false); - - $axure.page.bind('load.start', function () { - $axure.player.resizeContent(); - }); - - } - - // Always append both mobile browser menu and native menu, as app might not have returned value signifying native at this point - appendNativePrototypeControlFrame(); - appendMobileBrowserControlFrame(); - appendProjectOptions(); - } - - initializeLogo(); - initializePreview(); - - $axure.player.resizeContent(true); - - // Has timeout to keep waiting to build sign in controls while axAccount is still loading - initializeSignIn(); - })(); - }); - - function appendProjectOptions() { - var toAppend = ''; - toAppend += '<div id="projectOptionsHost" class="mobileOnlyPanel mobileMode">'; - toAppend += ' <div class="pluginNameHeader">PROJECT OPTIONS</div>'; - toAppend += ' <div id="projectOptionsScrollContainer">'; - toAppend += ' <div class="mobileSubHeader">Hotspots</div>'; - toAppend += ' <div id="projectOptionsShowHotspots" class="mobileText projectOptionsHotspotsRow" style="border-bottom: solid 1px #c7c7c7">'; - toAppend += ' <div id="projectOptionsHotspotsCheckbox"></div>'; - toAppend += ' Show Hotspots</div> '; - toAppend += ' <div class="mobileSubHeader" style="margin-top: 16px">Scale</div>'; - toAppend += ' <div id="projectOptionsScaleContainer" class="mobileText"></div>'; - toAppend += ' <div id="projectOptionsAdaptiveViewsHeader" class="mobileSubHeader" style="margin-top: 16px">Adaptive Views</div>'; - toAppend += ' <div id="projectOptionsAdaptiveViewsContainer" class="mobileText"></div>' - toAppend += ' </div>' - toAppend += '</div>'; - - $('#mHideSidebar').prepend(toAppend); - $(('#projectOptionsHost')).click(function (e) { e.stopPropagation(); }); - - if (isMobileMode()) $axure.player.resizeContent(); - } - - function appendMobileBrowserControlFrame() { - var toAppend = ""; - - toAppend += '<div id="mobileBrowserControlFrame" class="mobilePrototypeControlFrame">'; - toAppend += ' <div id="return" style="width:100%; position:relative; top:-15px; float:left">'; - toAppend += ' <div id="closeBackground" class="circleBackground">'; - toAppend += ' <div id="forwardSlash" class="closeIconSlash"><div id="backwardSlash" class="closeIconSlash"></div></div>'; - toAppend += ' </div>'; - toAppend += ' </div>'; - toAppend += '</div>'; - - $('#mobileControlFrameContainer').append(toAppend); - - $('#closeBackground').click(collapse); - - // iOS will do incorrect click position / content bounds calculation which results in scroll getting reset to (0, 0) - if (IOS) $('#mobileControlFrameContainer').on($axure.eventNames.mouseDownName, function (e) { e.stopPropagation(); }); - } - - function appendNativePrototypeControlFrame() { - var toAppend = ""; - toAppend += '<div id="nativeAppControlFrame" class="mobilePrototypeControlFrame">'; - toAppend += ' <ul id="nativeMenuBlueBackground">'; - toAppend += ' <li style="width:30%; float:left;">'; - toAppend += ' <div id="exit" class="nativePrototypeButton" >'; - toAppend += ' <div>'; - toAppend += ' <div id="exitIcon"></div>'; - toAppend += ' <div id="exitText" class="nativeMenuText">Exit</div>'; - toAppend += ' </div>'; - toAppend += ' </div>'; - toAppend += ' </li>'; - toAppend += ' <li id="return" style="width:40%; position:relative; top:-15px; float:left">'; - toAppend += ' <div id="returnBackground" class="circleBackground">'; - toAppend += ' <div id="returnIcon"></div>'; - toAppend += ' </div>'; - toAppend += ' <div id="returnText" class="nativeMenuText">Return to Prototype</div>'; - toAppend += ' </li>'; - toAppend += ' <li style="width:30%; float:right;">'; - toAppend += ' <div id="refresh" class="nativePrototypeButton" >'; - toAppend += ' <div>'; - toAppend += ' <div id="refreshIcon"></div>'; - toAppend += ' <div id="refreshText" class="nativeMenuText">Refresh</div>'; - toAppend += ' </div>'; - toAppend += ' </div>'; - toAppend += ' </li>'; - toAppend += ' </ul>'; - toAppend += '</div>'; - - $('#mobileControlFrameContainer').append(toAppend); - - var barHeight = IOS ? '72px' : '60px'; - var returnIconDisplacement = IOS ? '-15px': '-20px'; - var iconTopMargin = IOS ? '14px': '7px'; - var returnTextTopMargin = IOS ? '9px': '7px'; - - document.getElementById('nativeAppControlFrame').style.height = barHeight; - document.getElementById('nativeMenuBlueBackground').style.height = barHeight; - document.getElementById('return').style.top = returnIconDisplacement; - document.getElementById('returnText').style.marginTop = returnTextTopMargin; - document.getElementById('refreshIcon').style.marginTop = iconTopMargin; - document.getElementById('exitIcon').style.marginTop = iconTopMargin; - - addAppButtonClickListener("exit"); - addAppButtonClickListener("refresh"); - - $('#returnBackground').click(collapse); - $('#nativeAppControlFrame').on('touchmove', function (e) { - e.stopPropagation(); - }, false); - } - - function addAppButtonClickListener(id) { - var func = function () { IOS ? window.webkit.messageHandlers.prototypeMenuButtonClick.postMessage(id) : ShareApp.PrototypeMenuButtonClick(id); }; - document.getElementById(id).addEventListener("click", func, false); - } - - function toggleSitemap() { - $axure.player.showPlugin(1); - } - - function closePopup() { - var $container = $('.popup'); - var isLeftPanel = $container.hasClass('leftPanel'); - $container.removeClass('popup'); - $('#overflowMenuButton').removeClass('selected'); - $('#interfaceAdaptiveViewsContainer').removeClass('selected'); - $container.hide(); - - $('div.splitterMask').unbind($axure.eventNames.mouseDownName, closePopup); - $('div.splitterMask').remove(); - } - - $axure.player.closePopup = closePopup; - - function showPopup($container) { - if ($('#browserOutOfDateNotification').is(":visible")) return; - $container.addClass('popup'); - $container.show(); - - $('<div class="splitterMask"></div>').insertAfter($container); - $('div.splitterMask').bind($axure.eventNames.mouseDownName, closePopup); - } - - $axure.player.showPopup = showPopup; - - function toggleAdaptiveViewsPopup() { - if (($('#interfaceAdaptiveViewsListContainer').hasClass('popup'))) { - closePopup(); - } else { - $('#interfaceAdaptiveViewsContainer').addClass('selected'); - showPopup($('#interfaceAdaptiveViewsListContainer')); - } - } - - function toggleOverflowMenuPopup() { - if (($('#overflowMenuContainer').hasClass('popup'))) { - closePopup(); - } else { - $('#overflowMenuButton').addClass('selected'); - showPopup($('#overflowMenuContainer')); - } - } - - - var startSplitX; - var startSplitWidth; - function startLeftSplit() { - startSplitX = window.event.pageX; - startSplitWidth = lastLeftPanelWidth; - var $left = $('#lsplitbar'); - $left.addClass('active'); - $('<div class="splitterMask"></div>').insertAfter($left); - $(document).bind($axure.eventNames.mouseMoveName, doLeftSplitMove).bind($axure.eventNames.mouseUpName, endLeftSplitMove); - } - - function startRightSplit() { - startSplitX = window.event.pageX; - startSplitWidth = lastRightPanelWidth; - var $left = $('#rsplitbar'); - $left.addClass('active'); - $('<div class="splitterMask"></div>').insertAfter($left); - $(document).bind($axure.eventNames.mouseMoveName, doRightSplitMove).bind($axure.eventNames.mouseUpName, endRightSplitMove); - } - - function doLeftSplitMove() { - var currentX = window.event.pageX; - var newWidth = Math.min(startSplitWidth + currentX - startSplitX, $(window).width() - $('.rightPanel').width(), $(window).width() - lastRightPanelWidthDefault); - lastLeftPanelWidth = Math.max(lastLeftPanelWidthDefault, newWidth); - $('.leftPanel').width(lastLeftPanelWidth ? lastLeftPanelWidth : lastLeftPanelWidthDefault); - $('#lsplitbar').css('left', $('.leftPanel').width() - 4); - $axure.player.updateClippingBoundsWidth(); - $axure.player.refreshViewPort(); - } - - function doRightSplitMove() { - var currentX = window.event.pageX; - var newWidth = Math.min(startSplitWidth - currentX + startSplitX, $(window).width() - $('.leftPanel').width(), $(window).width() - lastLeftPanelWidthDefault); - lastRightPanelWidth = Math.max(lastRightPanelWidthDefault, newWidth); - $('.rightPanel').width(lastRightPanelWidth ? lastRightPanelWidth : lastRightPanelWidthDefault); - $('#rsplitbar').css('left', $(window).width() - $('.rightPanel').width()); - $axure.player.updateClippingBoundsWidth(); - $axure.player.refreshViewPort(); - } - - function endLeftSplitMove() { - $('div.splitterMask').remove(); - var $left = $('#lsplitbar'); - $left.removeClass('active'); - $(document).unbind($axure.eventNames.mouseMoveName, doLeftSplitMove).unbind($axure.eventNames.mouseUpName, endLeftSplitMove); - setAdaptiveView() - } - - function endRightSplitMove() { - $('div.splitterMask').remove(); - var $left = $('#rsplitbar'); - $left.removeClass('active'); - $(document).unbind($axure.eventNames.mouseMoveName, doRightSplitMove).unbind($axure.eventNames.mouseUpName, endRightSplitMove); - setAdaptiveView() - } - - - var startMX; - var startMLeft; - var startMElement; - var maxMLeft; - var getMaxMLeft = function () { - if ($('.rightPanel.mobileMode').length == 0) return $('.leftPanel.mobileMode').last().position().left + 100; - return $('.rightPanel.mobileMode').last().position().left + 100; - } - - function startM(e) { - // Android touch event does not define pageX directly - if(window.event.pageX) { - startMX = window.event.pageX; - } else { - startMX = window.event.touches[0].pageX; - } - - startMElement = window.event.target.id; - var $m = $('#mHideSidebar'); - startMLeft = Number($m.css('left').replace('px', '')); - $(document).bind($axure.eventNames.mouseMoveName, doMMove).bind($axure.eventNames.mouseUpName, endMMove); - - // Must stop propagation on iOS; otherwise scroll position of content will be reset to (0, 0) - // (likely due to position of click being calculated as out of bounds for outerContainer -- iOS is not adding scroll offset to bounds) - if (IOS) { e.stopPropagation() }; - } - - function doMMove() { - var $m = $('#mHideSidebar'); - if(window.event.pageX) { - currentX = window.event.pageX; - } else { - currentX = window.event.touches[0].pageX; - } - - var deltaX = currentX - startMX; - if (Math.abs(deltaX) > 0 && $('.splitterMask').length == 0) { - $('<div class="splitterMask"></div>').insertAfter($m); - } - var newLeft = startMLeft + deltaX; - newLeft = Math.min(0, newLeft); - newLeft = Math.max(-getMaxMLeft(), newLeft); - $m.css('left', newLeft + 'px'); - } - - function endMMove(e) { - $('div.splitterMask').remove(); - $(document).unbind($axure.eventNames.mouseMoveName, doMMove).unbind($axure.eventNames.mouseUpName, endMMove); - e.stopPropagation(); - - var $m = $('#mHideSidebar'); - if(window.event.pageX) { - currentX = window.event.pageX; - } else { - currentX = window.event.changedTouches[0].pageX; - } - var deltaX = currentX - startMX; - if (deltaX != 0 || startMElement != 'mHideSidebar') { - adjustM(currentX < startMX ? 'left' : 'right', true); - } - } - - function adjustM(direction, animate) { - var $m = $('#mHideSidebar'); - var duration = animate ? 100 : 0; - var newLeft = Number($m.css('left').replace('px', '')); - if (!$m.is(':visible') || newLeft > -100) { - $m.animate({ 'left': '-60px' }, duration); - } else if (newLeft < -getMaxMLeft() + 100) { - $m.animate({ 'left': (-getMaxMLeft() + 125) + 'px' }, duration); - } else if (direction == 'left') { - var handled = false; - var $panels = $('.rightPanel.mobileMode, .leftPanel.mobileMode'); - $panels.each(function () { - var panelX = $(this).position().left; - if (panelX > -newLeft) { - $m.animate({ 'left': (-panelX + 25) + 'px' }, duration); - handled = true; - return false; - } - }); - if (!handled) { - $m.animate({ 'left': (-$panels.last().position().left + 25) + 'px' }, duration); - } - } else if (direction == 'right') { - var handled = false; - var $panels = $('.rightPanel.mobileMode, .leftPanel.mobileMode'); - $($panels.get().reverse()).each(function () { - var panelRight = $(this).position().left + $(this).width(); - if (panelRight < -newLeft + $(window).width()) { - $m.animate({ 'left': (-$(this).position().left + 25) + 'px' }, duration); - handled = true; - return false; - } - }); - if (!handled) { - $m.animate({ 'left': '-60px' }, duration); - } - } - } - - function repositionPinsOnScaleChange(data) { - var $pins = $('#existingPinsOverlay').children(); - for (var i = 0; i < $pins.length; i++) { - // calculate new position of pin - const left = parseFloat($($pins[i]).attr('data-x')); - const top = parseFloat($($pins[i]).attr('data-y')); - const width = $($pins[i]).width(); - const height = $($pins[i]).height(); - - // Get current scale of mainPanelContainer - // MainPanelContainer scaled without setContentScale message - var scale = $('#mainPanelContainer').css('transform'); - scale = (scale == "none") ? 1 : Number(scale.substring(scale.indexOf('(') + 1, scale.indexOf(','))); - const scaledLeft = (left * scale) - (width / 2); - const scaledTop = (top * scale) - (height / 2); - - - $($pins[i]).css('left', scaledLeft + 'px'); - $($pins[i]).css('top', scaledTop + 'px'); - } - - // Distance from left of project content to origin (used for pins positioning when on a centered page in Scale to Fit mode) - if (typeof data.contentOriginOffset !== "undefined") contentLeftOfOriginOffset = data.contentOriginOffset; - } - - function messageCenter_message(message, data) { - if (message == 'expandFrame') expand(); - else if (message == 'getCollapseFrameOnLoad' && $axure.player.settings.startCollapsed && !MOBILE_DEVICE) $axure.messageCenter.postMessage('collapseFrameOnLoad'); - else if (message == 'tripleClick') { - if ($axure.player.isMobileMode() || MOBILE_DEVICE) expand(); - } else if (message == 'setContentScale') { - if (data.clipToView) { - var scaleVal = $('.vpScaleOption').find('.selectedRadioButton').parent().attr('val'); - if (scaleVal == '2' || (!MOBILE_DEVICE && scaleVal == '0')) { - var scaleN = newScaleN = $('#mainPanel').width() / data.viewportWidth; - var hScaleN = ($('#mainPanel').height()) / data.viewportHeight; - if (hScaleN < scaleN) scaleN = newScaleN = hScaleN; - if(scaleVal == '0') scaleN = Math.min(1, scaleN); - var scale = 'scale(' + scaleN + ')'; - $('#mainPanelContainer').css({ - 'transform': scale, - 'transform-origin': '' - }); - } - } else { - if (data.scaleN != 1) { - var scale = 'scale(' + data.scaleN + ')'; - var width = 100 / data.scaleN + '%'; - var height = Number($('#mainPanelContainer').css('height').replace('px', '')) / data.scaleN + 'px'; - $('#mainPanelContainer').css({ - 'transform': scale, - 'transform-origin': '0px 0px', - 'width': width, - 'height': height - }); - //$('#clipFrameScroll').css('height' , height + 'px'); - //$('#mainFrame').css('height' , height + 'px'); - $('#clipFrameScroll').height(height); - $('#mainFrame').height(height); - } - } - - repositionPinsOnScaleChange(data); - repositionClippingBoundsScroll(); - // Fix for edge not redrawing content after scale change - if ($axure.browser.isEdge) { - newHeight = window.innerHeight - ((!isMobileMode() && $('#topPanel').is(':visible')) ? $('#topPanel').height() : 0); - newWidth = $(window).width(); - $('#outerContainer').height(newHeight).width(newWidth); - $('#mainPanel').height(newHeight); - $('#clippingBounds').height(newHeight); - } - } - } - - function loadVariablesFromUrl(removeVarFromUrl) { - let originalHashValues = window.location.href.substr(window.location.href.indexOf('#')) || ''; - let variables = {}; - const query = (originalHashValues.split(GLOBAL_VAR_NAME)[1] || ''); - - if(query.length > 0) { - $axure.utils.parseGlobalVars(query, function(varName, varValue) { - variables[varName] = varValue; - }); - - if(removeVarFromUrl) { - originalHashValues = originalHashValues.replace(GLOBAL_VAR_NAME, "").replace(query, ""); - replaceHash(originalHashValues); - } - } - - return variables; - } - - function getInitialUrl() { - var shortId = getHashStringVar(PAGE_ID_NAME); - var foundById = []; - if (shortId.length > 0) { - getPageUrlsById(shortId, foundById, undefined); - if (foundById.length == 1) return foundById[0]; - } - - var pageName = getHashStringVar(PAGE_URL_NAME); - if (pageName.length > 0) return pageName + ".html"; - else { - if (foundById.length > 0) return foundById[0]; - var url = getFirstPageUrl($axure.document.sitemap.rootNodes); - return (url ? url : "about:blank"); - } - } - - var getPageUrlsById = $axure.player.getPageUrlsById = function (packageId, foundById, nodes) { - if (!nodes) nodes = $axure.document.sitemap.rootNodes; - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (node.id == packageId) foundById.push(node.url); - var hasChildren = (node.children && node.children.length > 0); - if (hasChildren) { - getPageUrlsById(packageId, foundById, node.children); - } - } - } - - var getPageIdByUrl = $axure.player.getPageIdByUrl = function(url, nodes) { - if (!nodes) nodes = $axure.document.sitemap.rootNodes; - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (node.url == url) return node.id; - else { - var hasChildren = (node.children && node.children.length > 0); - if (hasChildren) { - var id = getPageIdByUrl(url, node.children); - if (id) return id; - } - } - } - return null; - } - - function getFirstPageUrl(nodes) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (node.url) return node.url; - else { - var hasChildren = (node.children && node.children.length > 0); - if (hasChildren) { - var url = getFirstPageUrl(node.children); - if (url) return url; - } - } - } - return null; - } - - function closePlayer() { - if ($axure.page.location) window.location.href = $axure.page.location; - else { - var pageFile = getInitialUrl(); - var currentLocation = window.location.toString(); - window.location.href = currentLocation.substr(0, currentLocation.lastIndexOf("/") + 1) + pageFile; - } - } - - function replaceHash(newHash) { - var currentLocWithoutHash = window.location.toString().split('#')[0]; - - //We use replace so that every hash change doesn't get appended to the history stack. - //We use replaceState in browsers that support it, else replace the location - if (typeof window.history.replaceState != 'undefined') { - try { - //Chrome 45 (Version 45.0.2454.85 m) started throwing an error here when generated locally (this only happens with sitemap open) which broke all interactions. - //try catch breaks the url adjusting nicely when the sitemap is open, but all interactions and forward and back buttons work. - //Uncaught SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'file:///C:/Users/Ian/Documents/Axure/HTML/Untitled/start.html#p=home' cannot be created in a document with origin 'null'. - window.history.replaceState(null, null, currentLocWithoutHash + newHash); - } catch (ex) { } - } else { - window.location.replace(currentLocWithoutHash + newHash); - } - } - - function collapse() { - if (IOS) { - $('body').off('touchstart'); - $('body').off('touchend'); - } - - if ($axure.player.isMobileMode()) { - $('#mHideSidebar').hide(); - $('#nativeAppControlFrame').hide(); - $('#mobileBrowserControlFrame').hide(); - } else { - $axure.player.deleteVarFromCurrentUrlHash('g'); - $axure.player.setVarInCurrentUrlHash('c', 1); - if (!MOBILE_DEVICE) $('#maximizePanelContainer').show(); - lastLeftPanelWidth = $('.leftPanel').width(); - lastRightPanelWidth = $('.rightPanel').width(); - - $('.leftPanel').hide(); - $('.rightPanel').hide(); - $('#topPanel').hide(); - - $('.splitbar').hide(); - $('#mainPanel').width($(window).width()); - $('#clippingBounds').width($(window).width()); - $('#clippingBounds').css('left', '0px'); - $(window).resize(); - - $(document).trigger('sidebarCollapse'); - $('#maximizeButton').addClass('rotated'); - } - } - - function expand() { - if ($axure.player.isMobileMode()) { - $('#mHideSidebar').show(); - $('#mobileControlFrameContainer').show(); - $axure.utils.isShareApp() ? $('#nativeAppControlFrame').show() : $('#mobileBrowserControlFrame').show(); - } else { - $minimizeContainer = $('#interfaceControlFrameMinimizeContainer'); - $minimizeContainer.removeClass('collapseHovered'); - $axure.player.deleteVarFromCurrentUrlHash('c'); - $('#maximizeButton').removeClass('rotated'); - $('#maximizePanelContainer').hide(); - $axure.player.restorePlugins(); - $('#topPanel').show(); - $(window).resize(); - - $(document).trigger('sidebarExpanded'); - } - } - - - function mainFrame_onload() { - if ($axure.page.pageName) document.title = $axure.page.pageName; - } - - function getQueryString(query) { - var qstring = self.location.href.split("?"); - if (qstring.length < 2) return ""; - return GetParameter(qstring, query); - } - - function GetParameter(qstring, query) { - var prms = qstring[1].split("&"); - var frmelements = new Array(); - var currprmeter, querystr = ""; - - for (var i = 0; i < prms.length; i++) { - currprmeter = prms[i].split("="); - frmelements[i] = new Array(); - frmelements[i][0] = currprmeter[0]; - frmelements[i][1] = currprmeter[1]; - } - - for (j = 0; j < frmelements.length; j++) { - if (frmelements[j][0].toLowerCase() == query.toLowerCase()) { - querystr = frmelements[j][1]; - break; - } - } - return querystr; - } - - $axure.player.setVarInCurrentUrlHash = function(varName, varVal) { - var newHash = $axure.utils.setHashStringVar(window.location.hash, varName, varVal); - - if (newHash != null) { - replaceHash(newHash); - } - } - - function deleteHashStringVar(currentHash, varName) { - var varWithEqual = varName + '='; - - var pageIndex = currentHash.indexOf('#' + varWithEqual); - if (pageIndex == -1) pageIndex = currentHash.indexOf('&' + varWithEqual); - if (pageIndex != -1) { - var newHash = currentHash.substring(0, pageIndex); - - var ampIndex = currentHash.indexOf('&', pageIndex + 1); - - //IF begin of string....if none blank, ELSE # instead of & and rest - //IF in string....prefix + if none blank, ELSE &-rest - if (newHash == '') { //beginning of string - newHash = ampIndex != -1 ? '#' + currentHash.substring(ampIndex + 1) : ''; - } else { //somewhere in the middle - newHash = newHash + (ampIndex != -1 ? currentHash.substring(ampIndex) : ''); - } - - return newHash; - } - - return null; - } - - $axure.player.deleteVarFromCurrentUrlHash = function(varName) { - var newHash = deleteHashStringVar(window.location.hash, varName); - - if (newHash != null) { - replaceHash(newHash); - } - }; - - function setUpController() { - - //$axure.utils = _axUtils; - - var _page = {}; - $axure.page = _page; - - $axure.utils.makeBindable(_page, ['load']); - - var _player = function () { - }; - $axure.player = _player; - - //----------------------------------------- - //Global Var array, getLinkUrl function and setGlobalVar listener are - //for use in setting global vars in page url string when clicking a - //page in the sitemap - //NEW: this is now also used when navigating to a new window/popup, - //if there are global variables on the urls - //----------------------------------------- - var _globalVars = loadVariablesFromUrl(true); - - //----------------------------------------- - //Used by getLinkUrl below to check if local server is running - //in order to send back the global variables as a query string - //in the page url - //----------------------------------------- - var _shouldSendVarsToServer = function () { - //If exception occurs (due to page in content frame being from a different domain, etc) - //then run the check without the url (which will end up checking against sitemap url) - try { - var mainFrame = document.getElementById("mainFrame"); - return $axure.shouldSendVarsToServer(mainFrame.contentWindow.location.href); - } catch (e) { - return $axure.shouldSendVarsToServer(); - } - }; - - var _getLinkUrl = function (baseUrl) { - var toAdd = ''; - for (var globalVarName in _globalVars) { - var val = _globalVars[globalVarName]; - if (val != null) { - if (toAdd.length > 0) toAdd += '&'; - toAdd += globalVarName + '=' + encodeURIComponent(val); - } - } - return toAdd.length > 0 ? baseUrl + (_shouldSendVarsToServer() ? '?' : '#') + toAdd + "&CSUM=1" : baseUrl; - }; - $axure.getLinkUrlWithVars = _getLinkUrl; - - $axure.messageCenter.addMessageListener(function (message, data) { - if (message == 'setGlobalVar') { - _globalVars[data.globalVarName] = data.globalVarValue; - } - }); - - $axure.messageCenter.addStateListener('page.data', function (key, value) { - for (var subKey in value) { - _page[subKey] = value[subKey]; - } - $axure.page.triggerEvent('load'); - }); - - // --------------------------------------------- - // Navigates the main frame (setting the currently visible page). If the link is relative, - // this method should test if it is actually a axure rp page being loaded and properly set - // up all the controller for the page if it is - // --------------------------------------------- - _page.navigate = function (url, includeVariables) { - var mainFrame = document.getElementById("mainFrame"); - //var mainFrame = window.parent.mainFrame; - // if this is a relative url... - var urlToLoad; - if (url.indexOf(':') < 0 || url[0] == '/') { - var winHref = window.location.href; - var page = winHref.substring(0, winHref.lastIndexOf('/') + 1) + url; - urlToLoad = page; - } else { - urlToLoad = url; - } - if (!includeVariables) { - mainFrame.contentWindow.location.href = urlToLoad; - return; - } - var urlWithVars = $axure.getLinkUrlWithVars(urlToLoad); - var currentData = $axure.messageCenter.getState('page.data'); - var currentUrl = currentData && currentData.location; - if (currentUrl && currentUrl.indexOf('#') != -1) currentUrl = currentUrl.substring(0, currentUrl.indexOf('#')) - - // this is so we can make sure the current frame reloads if the variables have changed - // by default, if the location is the same but the hash code is different, the browser will not - // trigger a reload - mainFrame.contentWindow.location.href = - currentUrl && urlToLoad.toLowerCase() != currentUrl.toLowerCase() - ? urlWithVars - : 'resources/reload.html#' + encodeURI(urlWithVars); - - }; - - var pluginIds = []; - var plugins = {}; - var currentVisibleHostId = {}; - // --------------------------------------------- - // Adds a tool box frame from a url to the interface. This is useful for loading plugins - // settings is an object that supports the following properties: - // - id : the id of the element for the plugin - // - context : the context to create the plugin host for - // - title : the user-visible caption for the plugin - // --------------------------------------------- - _player.createPluginHost = function (settings) { - if (!settings.context || !(settings.context === 'project' || settings.context === 'inspect')) { - //throw ('unknown context type'); - return false; - } - - if (settings.id == 'feedbackHost') - $('#overflowMenuContainer').prepend('<div id="showCommentsOption" class="showOption" style="order: 2"><div class="overflowOptionCheckbox"></div>Show Comments</div>'); - - if (!settings.id) throw ('each plugin host needs an id'); - - if (typeof PREVIEW_INFO === 'undefined') { - // Share-Hosted Prototype - if (settings.id == 'debugHost') { return false; } - if (settings.id == 'handoffHost') { $('#handoffControlFrameHeaderContainer').show(); } - } else { - // Preview Mode - if (settings.id == 'handoffHost') { return false; } - } - - pluginIds[pluginIds.length] = settings.id; - plugins[settings.id] = settings; - - var hostContainerId = settings.context + 'ControlFrameHostContainer'; - hostContainerId = _player.isMobileMode() ? 'mHideSidebar' : 'outerContainer'; - var panelClass = 'rightPanel'; - var host; - if (settings.context == 'project') { - panelClass = 'leftPanel'; - if (_player.isMobileMode() && $('#' + hostContainerId).find('#projectOptionsHost').length > 0) { - host = $('<div id="' + settings.id + '" class="' + panelClass + '"></div>') - .insertAfter('#projectOptionsHost'); - } else { - host = $('<div id="' + settings.id + '" class="' + panelClass + '"></div>') - .prependTo('#' + hostContainerId); - } - } else { - if (!$('#separatorContainer').hasClass('hasLeft')) $('#separatorContainer').addClass('hasLeft'); - host = $('<div id="' + settings.id + '" class="' + panelClass + '"></div>') - .appendTo('#' + hostContainerId); - } - - $(('#' + settings.id)).click(function (e) { e.stopPropagation(); }); - - var controlContainerId = getControlContainerId(settings.id); - - - if (!_player.isMobileMode()) host.hide(); - else _player.updatePlugins(); - - // TODO: border radius in ie and edge causes image to be blurry (for now, just remove border-radius) - var style = (IE || $axure.browser.isEdge) ? '" style="border-radius: 0': ''; - var headerLink = $('<a pluginId="' + settings.id + '" title="' + settings.title + style + '" >' + (settings.context === 'inspect' ? ('<span>' + '</span>'): ' ') + '</a>'); - headerLink.mousedown($axure.utils.curry(interfaceControlHeaderButton_click, settings.id)).wrap('<li id="' + settings.id + 'Btn"' + (settings.id == "handoffHost" ? ' style="display: none"' : '') + '>'); - - headerLink.parent().appendTo('#' + controlContainerId); - - if (_player.isMobileMode()) $axure.player.resizeContent(); - - $(document).trigger('pluginCreated', [settings.gid]); - }; - - var getControlContainerId = function (id) { - return plugins[id].context + 'ControlFrameHeader'; - } - - var getVisiblePlugins = function () { - var ids = ''; - for (var id in plugins) { - var context = plugins[id].context; - if (currentVisibleHostId[context] == id) { - ids += plugins[id].gid; - } - } - return ids; - } - - _player.pluginVisibleChanged = function(hostId, visible) { - if (plugins[hostId]) { - $axure.messageCenter.postMessage('pluginVisibleChanged', { id: hostId, gid: plugins[hostId].gid, visible: visible }); - } - } - - var interfaceControlHeaderButton_click = function (id) { - if (_player.isAnimating) { return; } - $axure.player.closePopup(); - - var controlContainerId = getControlContainerId(id); - var context = plugins[id].context; - - var clickedPlugin = $('#' + controlContainerId + ' a[pluginId=' + id + ']'); - if (currentVisibleHostId[context] == id) { - clickedPlugin.removeClass('selected'); - if (id == "sitemapHost") { $('#sitemapControlFrameContainer').removeClass('selected'); } - currentVisibleHostId[context] = -1; - _player.collapseToBar(context, id); - - $(document).trigger('pluginShown', [getVisiblePlugins()]); - } else { - $('#' + controlContainerId + ' a').removeClass('selected'); - clickedPlugin.addClass('selected'); - if (id == "sitemapHost") { $('#sitemapControlFrameContainer').addClass('selected'); } - - $('#' + currentVisibleHostId[context]).hide(); - $axure.player.pluginVisibleChanged(currentVisibleHostId[context], false); - currentVisibleHostId[context] = id; - _player.expandFromBar(id, context); - - $(document).trigger('pluginShown', [getVisiblePlugins()]); - } - }; - - _player.pluginClose = function (id) { - var controlContainerId = getControlContainerId(id); - var context = plugins[id].context; - - var clickedPlugin = $('#' + controlContainerId + ' a[pluginId=' + id + ']'); - if (!clickedPlugin.hasClass('selected')) { return; } - clickedPlugin.removeClass('selected'); - currentVisibleHostId[context] = -1; - _player.collapseToBar(context, id); - - $(document).trigger('pluginShown', [getVisiblePlugins()]); - }; - - _player.showPlugin = function (gid) { - for (var id in plugins) { - if (plugins[id].gid == gid) { - interfaceControlHeaderButton_click(id); - break; - } - } - }; - - _player.restorePlugins = function () { - var selectedPluginsCount = 0; - for (var id in plugins) { - var clickedPlugin = $('#' + getControlContainerId(id) + ' a[pluginId=' + id + ']'); - if (clickedPlugin.hasClass('selected')) selectedPluginsCount++; - } - if ($axure.player.settings.isAxshare && selectedPluginsCount != 0) $('#clippingBoundsScrollContainer').hide(); - - var selectedPluginsSeen = 0; - for (var id in plugins) { - var controlContainerId = getControlContainerId(id); - var context = plugins[id].context; - var clickedPlugin = $('#' + controlContainerId + ' a[pluginId=' + id + ']'); - if (clickedPlugin.hasClass('selected')) { - //_player.showPlugin(id); - // TODO: handoffHost would need center inspect icon highlighted and rightFrameIcon set to visible - //if (id == 'handoffHost') { } - //$('#' + id).show(); - selectedPluginsSeen++; - _player.expandFromBar(id, context, selectedPluginsCount == selectedPluginsSeen); - } else { - $('#' + id).hide(); - } - } - $(document).trigger('pluginShown', [getVisiblePlugins()]); - }; - - _player.navigateToIssue = function (issueId) { - if (typeof feedback !== 'undefined') { - feedback.navigateToIssue(issueId); - } - }; - } - - - $axure.player.hideAllPlayerControllers = function(isVisible) { - // TOOD: Verify that the containers are set to the right state after re-enabling them - if(isVisible) { - $('#topPanel').css('display', ''); - $('#popupContainer').css('display', ''); - $('#maximizePanelContainer').css('display', ''); - $('#mobileControlFrameContainer').css('display', ''); - } else { - $('#topPanel').hide(); - $('#popupContainer').hide(); - $('#maximizePanelContainer').hide(); // TODO: This needs to have a function where it prevents itself from showing up externally - $('#mobileControlFrameContainer').hide(); - } - } - - - // TODO: General function to add bezels/overlays if applicable - $axure.player.addDeviceFraming = function (project, isEdit) { - // Temporary - var devices = { - iPhone8: 0, - iPhone8Plus: 1, - iPhoneSE: 2, - iPhoneX: 3, - iPad4: 4, - GalaxyS8: 5, - Pixel2: 6, - Pixel2XL: 7, - Mobile: 8, - Tablet9: 9, - Tablet7: 10, - Custom: 11, - Web: 12 - }; - - // TODO: Need to bring over some platform functionality -> function might not be present - if (!$axure.player.settings.isExpo || project.Platform.Device === 12) { return; } - - // TODO: Generate html for overlay and bezel containers - // TODO: Determine if preview player or full prototype player to establish where containers will be stored - var currDevice = project.Platform.Device; - var rootPath = '../../Scripts/Expo/StaticContent/resources/images/mobile/'; - var framePath, overlayPath; - - var $overlayParent = $(window.parent.parent.document).find('#previewPlayerDiv'); - $overlayParent = isEdit && $overlayParent.length !== 0 ? $overlayParent : $('#mainPanelContainer'); - - $overlayParent.css('overflow', 'visible'); - - // TODO: Import enum of Device types -> import via TS definitions. WILL NEED TO REMEMBER THAT WE NEED TO SYNC SERVER AND CLIENT SIDE - // TODO: Create mapping of required images to device type - // images will be stored in ../../images/mobile - // TODO: Manage resizing - // TODO: Manage pointer clicks - // TODO: Status bar -> Default or via settings - - - // TODO: Establish img paths - switch (currDevice) { - case devices.iPhone8: - case devices.iPhone8Plus: - framePath = rootPath + 'iphone.svg'; - overlayPath = ""; - break; - case devices.iPhoneSE: - break; - case devices.iPhoneX: - framePath = ""; - overlayPath = ""; - break; - case devices.iPad4: - break; - case devices.Pixel2: - break; - case devices.Pixel2XL: - break; - case devices.GalaxyS8: - break; - case devices.Mobile: - case devices.Tablet7: - case devices.Tablet9: - case devices.Custom: - default: - break; - } - - // TODO: Append images - // TODO: Position and initial dimensions - // TODO: Add resize handlers (?) - // TODO: Add pointer event handers (?) - if (framePath != undefined) { - $overlayParent.prepend(genFrameContainer()); - - var $fContainer = $overlayParent.find('#deviceFrameContainer'); - var $frame = $fContainer.find('#deviceFrame'); - - $frame.css('background-image', "url('" + framePath + "')"); - $frame.css('height', ''); - $frame.css('width', ''); - $frame.css('top', ''); - $frame.css('left', ''); - - if(isEdit) { - $fContainer.css('z-index', -1); - } - } - - if (overlayPath != undefined) { - // TODO: Update for edit mode - // $overlayParent.append(genOverlayContainer()); - - var $oContainer = $overlayParent.find('#deviceOverlayContainer'); - var $overlay = $oContainer.find('#deviceOverlay'); - - $overlay.css('background-image', "url('" + overlayPath + "')"); - } - } - - function genFrameContainer(bezelPath) { - var container = [ - '<div id="deviceFrameContainer">', - ' <div id="deviceFrame">', - ' </div>', - '</div>' - ].join(""); - - return container; - } - -})(); diff --git a/web/main/static/resources/scripts/player/init.js b/web/main/static/resources/scripts/player/init.js deleted file mode 100644 index 0f9fcd5..0000000 --- a/web/main/static/resources/scripts/player/init.js +++ /dev/null @@ -1,18 +0,0 @@ -(function () { - $.holdReady(true); - - var script = window.document.createElement("script"); - script.type = "text/javascript"; - script.async = true; - script.onload = script.onreadystatechange = function (e, isAbort) { - if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { - script.onload = script.onreadystatechange = null; - script = undefined; - } - - if (!isAbort) { $.holdReady(false); } - } - - script.src = "data/document.js"; - window.document.head.appendChild(script); -})(); \ No newline at end of file diff --git a/web/main/static/resources/scripts/player/splitter.js b/web/main/static/resources/scripts/player/splitter.js deleted file mode 100644 index 068eead..0000000 --- a/web/main/static/resources/scripts/player/splitter.js +++ /dev/null @@ -1,219 +0,0 @@ -/* -* jQuery.splitter.js - two-pane splitter window plugin -* -* version 1.51 (2009/01/09) -* -* Dual licensed under the MIT and GPL licenses: -* http://www.opensource.org/licenses/mit-license.php -* http://www.gnu.org/licenses/gpl.html -*/ - -/** -* The splitter() plugin implements a two-pane resizable splitter window. -* The selected elements in the jQuery object are converted to a splitter; -* each selected element should have two child elements, used for the panes -* of the splitter. The plugin adds a third child element for the splitbar. -* -* For more details see: http://methvin.com/splitter/ -* -* -* @example $('#MySplitter').splitter(); -* @desc Create a vertical splitter with default settings -* -* @example $('#MySplitter').splitter({type: 'h', accessKey: 'M'}); -* @desc Create a horizontal splitter resizable via Alt+Shift+M -* -* @name splitter -* @type jQuery -* @param Object options Options for the splitter (not required) -* @cat Plugins/Splitter -* @return jQuery -* @author Dave Methvin (dave.methvin@gmail.com) -*/ -;(function($){ - -$.fn.splitter = function(args){ - args = args || {}; - return this.each(function() { - var zombie; // left-behind splitbar for outline resizes - function startSplitMouse(evt) { - if ( opts.outline ) - zombie = zombie || bar.clone(false).insertAfter(A); - panes.css("-webkit-user-select", "none"); // Safari selects A/B text on a move - bar.addClass(opts.activeClass); - $('<div class="splitterMask"></div>').insertAfter(bar); - A._posSplit = A[0][opts.pxSplit] - evt[opts.eventPos]; - $(document) - .bind("mousemove", doSplitMouse) - .bind("mouseup", endSplitMouse); - } - function doSplitMouse(evt) { - var newPos = A._posSplit+evt[opts.eventPos]; - if ( opts.outline ) { - newPos = Math.max(0, Math.min(newPos, splitter._DA - bar._DA)); - bar.css(opts.origin, newPos); - } else - resplit(newPos); - } - function endSplitMouse(evt) { - $('div.splitterMask').remove(); - bar.removeClass(opts.activeClass); - var newPos = A._posSplit+evt[opts.eventPos]; - if ( opts.outline ) { - zombie.remove(); zombie = null; - resplit(newPos); - } - panes.css("-webkit-user-select", "text"); // let Safari select text again - $(document) - .unbind("mousemove", doSplitMouse) - .unbind("mouseup", endSplitMouse); - } - function resplit(newPos) { - // Constrain new splitbar position to fit pane size limits - newPos = Math.max(A._min, splitter._DA - B._max, - Math.min(newPos, A._max, splitter._DA - bar._DA - B._min)); - // Resize/position the two panes - bar._DA = bar[0][opts.pxSplit]; // bar size may change during dock - - var posOffset = bar.is(':visible') ? bar._DA - 1 : 0; - - bar.css(opts.origin, newPos - posOffset).css(opts.fixed, splitter._DF); - A.css(opts.origin, 0).css(opts.split, newPos).css(opts.fixed, splitter._DF); - B.css(opts.origin, newPos + bar._DA - posOffset) - .css(opts.split, splitter._DA-bar._DA-newPos).css(opts.fixed, splitter._DF); - // IE fires resize for us; all others pay cash - if ( !IE_10_AND_BELOW ) - panes.trigger("resize"); - } - function dimSum(jq, dims) { - // Opera returns -1 for missing min/max width, turn into 0 - var sum = 0; - for ( var i=1; i < arguments.length; i++ ) - sum += Math.max(parseInt(jq.css(arguments[i])) || 0, 0); - return sum; - } - - // Determine settings based on incoming opts, element classes, and defaults - var vh = (args.splitHorizontal? 'h' : args.splitVertical? 'v' : args.type) || 'v'; - var opts = $.extend({ - activeClass: 'active', // class name for active splitter - pxPerKey: 8, // splitter px moved per keypress - tabIndex: 0, // tab order indicator - accessKey: '' // accessKey for splitbar - },{ - v: { // Vertical splitters: - keyLeft: 39, keyRight: 37, cursor: "col-resize", - splitbarClass: "vsplitbar", outlineClass: "voutline", - type: 'v', eventPos: "pageX", origin: "left", - split: "width", pxSplit: "offsetWidth", side1: "Left", side2: "Right", - fixed: "height", pxFixed: "offsetHeight", side3: "Top", side4: "Bottom" - }, - h: { // Horizontal splitters: - keyTop: 40, keyBottom: 38, cursor: "row-resize", - splitbarClass: "hsplitbar", outlineClass: "houtline", - type: 'h', eventPos: "pageY", origin: "top", - split: "height", pxSplit: "offsetHeight", side1: "Top", side2: "Bottom", - fixed: "width", pxFixed: "offsetWidth", side3: "Left", side4: "Right" - } - }[vh], args); - - // Create jQuery object closures for splitter and both panes - var splitter = $(this).css({position: "relative"}); - var panes = $(">*", splitter[0]).css({ - position: "absolute", // positioned inside splitter container - "z-index": "1", // splitbar is positioned above - "-moz-outline-style": "none" // don't show dotted outline - }); - var A = $(panes[0]); // left or top - var B = $(panes[1]); // right or bottom - - // Focuser element, provides keyboard support; title is shown by Opera accessKeys - var focuser = $('<a href="javascript:void(0)"></a>') - .attr({accessKey: opts.accessKey, tabIndex: opts.tabIndex, title: opts.splitbarClass}) - //.bind($.browser.opera?"click":"focus", function(){ this.focus(); bar.addClass(opts.activeClass) }) - .bind("focus", function () { this.focus(); bar.addClass(opts.activeClass) }) - .bind("keydown", function(e){ - var key = e.which || e.keyCode; - var dir = key==opts["key"+opts.side1]? 1 : key==opts["key"+opts.side2]? -1 : 0; - if ( dir ) - resplit(A[0][opts.pxSplit]+dir*opts.pxPerKey, false); - }) - .bind("blur", function(){ bar.removeClass(opts.activeClass) }); - - // Splitbar element, can be already in the doc or we create one - var bar = $(panes[2] || '<div></div>') - .insertAfter(A).css("z-index", "100").append(focuser) - .attr({"class": opts.splitbarClass, unselectable: "on"}) - .css({position: "absolute", "user-select": "none", "-webkit-user-select": "none", - "-khtml-user-select": "none", "-moz-user-select": "none", "top": "0px"}) - .bind("mousedown", startSplitMouse); - // Use our cursor unless the style specifies a non-default cursor - if ( /^(auto|default|)$/.test(bar.css("cursor")) ) - bar.css("cursor", opts.cursor); - - // Cache several dimensions for speed, rather than re-querying constantly - bar._DA = bar[0][opts.pxSplit]; - splitter._PBF = $.boxModel? dimSum(splitter, "border"+opts.side3+"Width", "border"+opts.side4+"Width") : 0; - splitter._PBA = $.boxModel? dimSum(splitter, "border"+opts.side1+"Width", "border"+opts.side2+"Width") : 0; - A._pane = opts.side1; - B._pane = opts.side2; - $.each([A,B], function(){ - this._min = opts["min"+this._pane] || dimSum(this, "min-"+opts.split); - this._max = opts["max"+this._pane] || dimSum(this, "max-"+opts.split) || 9999; - this._init = opts["size"+this._pane]===true ? - parseInt($.curCSS(this[0],opts.split)) : opts["size"+this._pane]; - }); - - // Determine initial position, get from cookie if specified - var initPos = A._init; - if ( !isNaN(B._init) ) // recalc initial B size as an offset from the top or left side - initPos = splitter[0][opts.pxSplit] - splitter._PBA - B._init - bar._DA; - if ( opts.cookie ) { - if ( !$.cookie ) - alert('jQuery.splitter(): jQuery cookie plugin required'); - var ckpos = parseInt($.cookie(opts.cookie)); - if ( !isNaN(ckpos) ) - initPos = ckpos; - $(window).bind("unload", function(){ - var state = String(bar.css(opts.origin)); // current location of splitbar - $.cookie(opts.cookie, state, {expires: opts.cookieExpires || 365, - path: opts.cookiePath || document.location.pathname}); - }); - } - if ( isNaN(initPos) ) // King Solomon's algorithm - initPos = Math.round((splitter[0][opts.pxSplit] - splitter._PBA - bar._DA)/2); - - // Resize event propagation and splitter sizing - if ( opts.anchorToWindow ) { - // Account for margin or border on the splitter container and enforce min height - splitter._hadjust = dimSum(splitter, "borderTopWidth", "borderBottomWidth", "marginBottom"); - splitter._hmin = Math.max(dimSum(splitter, "minHeight"), 20); - $(window).bind("resize", function(){ - var top = splitter.offset().top; - var wh = $(window).height(); - splitter.css("height", Math.max(wh-top-splitter._hadjust, splitter._hmin)+"px"); - if ( !IE_10_AND_BELOW ) splitter.trigger("resize"); - }).trigger("resize"); - } - else if ( opts.resizeToWidth && !IE_10_AND_BELOW ) - $(window).bind("resize", function(){ - splitter.trigger("resize"); - }); - - // Resize event handler; triggered immediately to set initial position - splitter.bind("resize", function(e, size){ - // Custom events bubble in jQuery 1.3; don't Yo Dawg - if ( e.target != this ) return; - // Determine new width/height of splitter container - splitter._DF = splitter[0][opts.pxFixed] - splitter._PBF; - splitter._DA = splitter[0][opts.pxSplit] - splitter._PBA; - // Bail if splitter isn't visible or content isn't there yet - if ( splitter._DF <= 0 || splitter._DA <= 0 ) return; - // Re-divvy the adjustable dimension; maintain size of the preferred pane - resplit(!isNaN(size)? size : (!(opts.sizeRight||opts.sizeBottom)? A[0][opts.pxSplit] : - splitter._DA-B[0][opts.pxSplit]-bar._DA)); - }).trigger("resize" , [initPos]); - }); -}; - -})(jQuery); \ No newline at end of file diff --git a/web/main/static/resources/scripts/system_manager.js b/web/main/static/resources/scripts/system_manager.js new file mode 100644 index 0000000..90058b6 --- /dev/null +++ b/web/main/static/resources/scripts/system_manager.js @@ -0,0 +1,440 @@ +let currentPage = 1; +const rowsPerPage = 10; +let currentEditingRow = null; +let areaData = []; +let areaData_bak = []; +//网络信息 +let wired_type; +let wired_ip; +let wired_mask; +let wired_gateway; +let wired_dns; +let wireless_type; +let wireless_ip; +let wireless_mask; +let wireless_gateway; +let wireless_dns; +let wireless_ssid; +let wireless_passwd; +let wifi_list = []; + +//页面加载初始化 +document.addEventListener('DOMContentLoaded', function () { + fetchSystemData(); //初始化系统信息 + fetchAreaData();//初始化区域信息 + //升级按钮 + document.getElementById('upsystem').addEventListener('click',function () {upgrade_system();}); + + //设备IP配置按钮--显示模态框 + document.getElementById('showIPConfig').addEventListener('click',function () {show_IPConfigModel();}); + //设备IP配置模态框--保存按钮 + document.getElementById('saveIPConfig').addEventListener('click',function () {save_IPConfig();}); + document.getElementById('connectWifi').addEventListener('click',function () {connect_wifi();}); + + //服务器IP配置 + document.getElementById('showServerIP').addEventListener('click',function () {show_ServerIPConfig();}); + document.getElementById('saveServerIP').addEventListener('click',function () {save_ServerIPConfig();}); + + //区域管理 + document.getElementById('addAreaButton').addEventListener('click',function () {show_AreaManager();}); + document.getElementById('addArea').addEventListener('click',function () {add_Area();}); + + //修改区域模态框 + document.getElementById('modifArea').addEventListener('click',function () {modify_Area();}); +}); + +//刷新系统信息 +async function fetchSystemData() { + try{ + let response = await fetch('/api/system/info'); + if (!response.ok) { + throw new Error('Network response was not ok'); + } + data = await response.json(); + + document.getElementById('system_version').textContent = data.version; + document.getElementById('dev_ID').textContent = data.ID; + document.getElementById('service_ip').value = data.service_ip; + document.getElementById('service_port').value = data.service_port; + //网络信息 + wired_type = data.wired_type; + wired_ip = data.wired_ip; + wired_mask = data.wired_mask; + wired_gateway = data.wired_gateway; + wired_dns = data.wired_dns; + wireless_type = data.wireless_type; + wireless_ip = data.wireless_ip; + wireless_mask = data.wireless_mask; + wireless_gateway = data.wireless_gateway; + wireless_dns = data.wireless_dns; + wireless_ssid = data.ssid; + wireless_passwd = data.wifi_passwd; + //wifi -list + wifi_list = data.wifi_list; + wifi_list.unshift("请选择"); + document.getElementById('dev_IP').textContent = `有线--${wired_ip} 无线--${wireless_ip}`; + + + }catch (error) { + console.error('Error fetching model data:', error); + } +} + +//刷新区域信息-- +async function fetchAreaData() { + try{ + let response = await fetch('/api/system/area'); + if (!response.ok) { + throw new Error('Network response was not ok'); + } + areaData = await response.json(); + areaData_bak = areaData; + currentPage = 1; // 重置当前页为第一页 + renderTable(); //刷新表格 + renderPagination(); + }catch (error) { + console.error('Error fetching model data:', error); + } +} + +//刷新表格 +function renderTable(){ + const tableBody = document.getElementById('table-body-area'); + tableBody.innerHTML = ''; + + const start = (currentPage - 1) * rowsPerPage; + const end = start + rowsPerPage; + const pageData = areaData.slice(start, end); + const surplus_count = rowsPerPage - pageData.length; + + pageData.forEach((area) => { + const row = document.createElement('tr'); + row.innerHTML = ` + <td>${area.ID}</td> + <td>${area.area_name}</td> + <td> + <button class="btn btn-primary btn-sm modify-btn">修改</button> + <button class="btn btn-danger btn-sm delete-btn">删除</button> + </td> + `; + tableBody.appendChild(row); + row.querySelector('.modify-btn').addEventListener('click', () => show_modify_Area(row)); + row.querySelector('.delete-btn').addEventListener('click', () => del_Area(row)); + }); +} + +//刷新分页标签 +function renderPagination() { + const pagination = document.getElementById('pagination-area'); + pagination.innerHTML = ''; + + const totalPages = Math.ceil(areaData.length / rowsPerPage); + for (let i = 1; i <= totalPages; i++) { + const pageItem = document.createElement('li'); + pageItem.className = 'page-item' + (i === currentPage ? ' active' : ''); + pageItem.innerHTML = `<a class="page-link" href="#">${i}</a>`; + pageItem.addEventListener('click', (event) => { + event.preventDefault(); + currentPage = i; + renderTable(); + renderPagination(); + }); + pagination.appendChild(pageItem); + } +} + +//系统升级 +async function upgrade_system(){ + alert("点击了系统升级按钮"); +} + +//设备IP地址配置 --- 显示模态框--------------------- +function show_IPConfigModel(){ + //wired页面 + const el_wired_dhcp = document.getElementById('dhcp_lan'); + const el_wired_static = document.getElementById('static_lan'); + const el_wired_ip = document.getElementById('wiredIpAddress'); + const el_wired_mask = document.getElementById('wiredSubnetMask'); + const el_wired_gateway = document.getElementById('wiredGateway'); + const el_wired_dns = document.getElementById('wiredDNS'); + if(wired_type==0){ //dhcp + el_wired_dhcp.checked = true; + }else{ + el_wired_static.checked = true; + } + el_wired_ip.value = wired_ip; + el_wired_mask.value = wired_mask; + el_wired_gateway.value = wired_gateway; + el_wired_dns.value = wired_dns; + + //wireless页面 + //document.getElementById('wirelessNetwork'); + + const el_wireless_passwd = document.getElementById('wifi_passwd'); + const el_wireless_dhcp = document.getElementById('dhcp_wifi'); + const el_wireless_static = document.getElementById('static_wifi'); + const el_wireless_ip = document.getElementById('wirelessIpAddress'); + const el_wireless_mask = document.getElementById('wirelessSubnetMask'); + const el_wireless_gateway = document.getElementById('wirelessGateway'); + const el_wireless_dns = document.getElementById('wirelessDNS'); + + //wireless_ssid = data.ssid; + //wireless_passwd = data.wifi_passwd; + if(wired_type==0){ //dhcp + el_wireless_dhcp.checked = true; + }else{ + el_wireless_static.checked = true; + } + set_select_data("wirelessNetwork",wifi_list); + if(wireless_ssid == null || wireless_ssid == ""){ + //控件不可操作 + el_wireless_dhcp.disabled=true; + el_wireless_static.disabled=true; + el_wireless_ip.disabled=true; + el_wireless_mask.disabled=true; + el_wireless_gateway.disabled=true; + el_wireless_dns.disabled=true; + }else{ + let bfind = set_select_selct("wirelessNetwork",wireless_ssid); + if(bfind== false){ + el_wireless_dhcp.disabled=true; + el_wireless_static.disabled=true; + el_wireless_ip.disabled=true; + el_wireless_mask.disabled=true; + el_wireless_gateway.disabled=true; + el_wireless_dns.disabled=true; + }else{ + el_wireless_passwd.value = wireless_passwd; + el_wireless_ip.value = wireless_ip; + el_wireless_mask.value = wireless_mask; + el_wireless_gateway.value = wireless_gateway; + el_wireless_dns.value = wireless_dns; + } + } + $('#ipConfigModal').modal('show'); +} +//点击连接wifi 按钮 +async function connect_wifi(){ + alert("点击了连接wifi按钮"); +} + +//设备IP地址配置 --- 点击保存按钮 +async function save_IPConfig(){ + alert("点击了设备IP保存按钮"); +} + +//IP配置模态框,单选按钮点击 +function handleRadioClick_lan(event){ + const selectedRadio = event.target; + const el_ip = document.getElementById('wiredIpAddress'); + const el_mask = document.getElementById('wiredSubnetMask'); + const el_gateway = document.getElementById('wiredGateway'); + const el_dns = document.getElementById('wiredDNS'); + let net_type = 0; //0--dhcp,1--static + if (selectedRadio.id === 'dhcp_lan') { + net_type = 1; + el_ip.disabled = true; + el_mask.disabled = true; + el_gateway.disabled = true; + el_dns.disabled = true; + } + else if(selectedRadio.id === 'static_lan'){ + net_type = 2; + el_ip.disabled = false; + el_mask.disabled = false; + el_gateway.disabled = false; + el_dns.disabled = false; + } +} + +//IP配置模态框,单选按钮点击 +function handleRadioClick_wifi(event){ + const selectedRadio = event.target; + let wifi_type = 0; //0--dhcp,1--static + const el_ip = document.getElementById('wirelessIpAddress'); + const el_mask = document.getElementById('wirelessSubnetMask'); + const el_gateway = document.getElementById('wirelessGateway'); + const el_dns = document.getElementById('wirelessDNS'); + if (selectedRadio.id === 'dhcp_wifi') { + net_type = 1; + el_ip.disabled = true; + el_mask.disabled = true; + el_gateway.disabled = true; + el_dns.disabled = true; + } + else if(selectedRadio.id === 'static_wifi'){ + net_type = 2; + el_ip.disabled = false; + el_mask.disabled = false; + el_gateway.disabled = false; + el_dns.disabled = false; + } + +} + +//服务器IP配置----------------------------------------- +function show_ServerIPConfig(){ + const el_serviceIP = document.getElementById('serviceIP_model'); + const el_servicePort = document.getElementById('servicePort_model'); + el_serviceIP.value = document.getElementById('service_ip').value; + el_servicePort.value = document.getElementById('service_port').value; + $('#ServerIPModal').modal('show'); +} + +async function save_ServerIPConfig(){ + const el_serverIP = document.getElementById('serviceIP_model'); + const el_serverPort = document.getElementById('servicePort_model'); + const btn = document.getElementById('saveServerIP'); + serverIP = el_serverIP.value; + serverPort = el_serverPort.value; + if(serverIP==="" || serverPort===""){ + alert("服务端IP和端口号不能为空!") + } + else{ + if(isValidIP(serverIP)){ + btn.disabled = true; + const formData = new FormData(); + formData.append('ip', serverIP); + formData.append('port', serverPort); + fetch("/api/system/changeserver", { + method: 'POST', + body: formData, + }) + .then(response => response.json()) + .then(data => { + btn.disabled = false; + const istatus = data.status; + alert(data.msg); + if(istatus == 1){ + fetchSystemData(); + $('#ServerIPModal').modal('hide'); + } + }) + .catch(error => { + console.error('Error:', error); + alert('修改失败,请重试。'); + btn.disabled = false; + }); + } + else{ + alert("请输入正确的IP地址!") + } + } +} + +//区域管理------------------------------------------- +function show_AreaManager(){ + $('#addAreaModal').modal('show'); +} + +async function add_Area(){ + const el_ereaname = document.getElementById('area_name'); + const btn = document.getElementById('addArea'); + area_name = el_ereaname.value; + if(area_name===""){ + alert("请输入区域名称"); + }else{ + btn.disabled = true; + //提交数据 + const url = '/api/channel/area/add'; + const data = {"name":area_name}; + // 发送 POST 请求 + fetch(url, { + method: 'POST', // 指定请求方法为 POST + headers: { + 'Content-Type': 'application/json' // 设置请求头,告诉服务器请求体的数据类型为 JSON + }, + body: JSON.stringify(data) // 将 JavaScript 对象转换为 JSON 字符串 + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + btn.disabled = false; + const istatus = data.status; + alert(data.msg); + if(istatus == 1){ + fetchAreaData(); + $('#addAreaModal').modal('hide'); + } + }) + .catch((error) => { + alert(`Error: ${error.message}`); + btn.disabled = false; + }); + } +} + +//显示修改区域信息 +function show_modify_Area(row){ + currentEditingRow = row; + area_name = row.cells[1].innerText; + const el_areaname = document.getElementById('area_name_modif'); + el_areaname.value = area_name; + $('#modifyAreaModal').modal('show'); +} + +//点击修改模态框的保存按钮 +async function modify_Area(){ + area_id = currentEditingRow.cells[0].innerText; + area_name = document.getElementById('area_name_modif').value; + const btn = document.getElementById('modifArea'); + if(area_name===""){ + alert("请输入区域名称!") + }else{ + btn.disabled = true; + //提交数据 + const url = '/api/channel/area/change'; + const formData = new FormData(); + formData.append('name', area_name); + formData.append('id', area_id); + //const data = {"name":area_name,"id":area_id}; + // 发送 POST 请求 + fetch(url, { + method: 'POST', + body: formData, + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + btn.disabled = false; + const istatus = data.status; + alert(data.msg); + if(istatus == 1){ + fetchAreaData(); + $('#modifyAreaModal').modal('hide'); + } + }) + .catch((error) => { + alert(`Error: ${error.message}`); + btn.disabled = false; + }); + } +} + +//删除区域信息 +async function del_Area(row){ + if (confirm('确定删除此区域吗?')){ + currentEditingRow = row; + area_id =row.cells[0].innerText; + const url = '/api/channel/area/del'; + const formData = new FormData(); + formData.append('id', area_id); + //const data = {"name":area_name,"id":area_id}; + // 发送 POST 请求 + fetch(url, { + method: 'POST', + body: formData, + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + const istatus = data.status; + alert(data.msg); + if(istatus == 1){ + //刷新列表 + row.remove(); + } + }) + .catch((error) => { + alert(`Error: ${error.message}`); + btn.disabled = false; + }); + } +} \ No newline at end of file diff --git a/web/main/static/resources/scripts/user_manager.js b/web/main/static/resources/scripts/user_manager.js new file mode 100644 index 0000000..d91b025 --- /dev/null +++ b/web/main/static/resources/scripts/user_manager.js @@ -0,0 +1,48 @@ +document.getElementById('changePasswd').addEventListener('click',function () { + changePasswd(); +}); + +function changePasswd(){ + const el_oldpasswd = document.getElementById('source_passwd'); + const el_new_passwd = document.getElementById('new_passwd'); + const el_again_passwd = document.getElementById('again_passwd'); + const btn = document.getElementById('changePasswd'); + oldpasswd = el_oldpasswd.value; + newpasswd = el_new_passwd.value; + againpasswd = el_again_passwd.value; + if(oldpasswd === "" || newpasswd === "" || againpasswd === ""){ + alert("密码不能为空!") + }else{ + if(newpasswd !== againpasswd){ + alert("两次输入的密码不相同!") + }else{ + btn.disabled = true; + //提交请求 + const url = "/api/user/passwd" + const data = {"oldpasswd":oldpasswd,"newpasswd":newpasswd}; + fetch(url, { + method: 'POST', // 指定请求方法为 POST + headers: { + 'Content-Type': 'application/json' // 设置请求头,告诉服务器请求体的数据类型为 JSON + }, + body: JSON.stringify(data) // 将 JavaScript 对象转换为 JSON 字符串 + }) + .then(response => response.json()) // 将响应解析为 JSON + .then(data => { + btn.disabled = false; + const istatus = data.status; + alert(data.msg); + if(istatus == 1){ + el_oldpasswd.value = ""; + el_new_passwd.value = ""; + el_again_passwd.value = ""; + } + }) + .catch((error) => { + btn.disabled = false; + alert(`Error: ${error.message}`); + return; + }); + } + } +} \ No newline at end of file diff --git a/web/main/templates/base.html b/web/main/templates/base.html index 4c43dd7..b9bbb53 100644 --- a/web/main/templates/base.html +++ b/web/main/templates/base.html @@ -11,6 +11,31 @@ vertical-align: -.125em; fill: currentColor; } + .form-label { + font-weight: bold; + font-size: 1.2rem; + } + .form-group { + margin-bottom: 1rem; + } + + #spinnerOverlay { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(255, 255, 255, 0.7); /* 半透明的背景 */ + display: flex; + justify-content: center; + align-items: center; + z-index: 1060; /* 确保在最上层显示 */ + } + /* 确保 Spinners 的大小合适 */ + #spinnerOverlay .spinner-border { + width: 3rem; + height: 3rem; + } {% block style %}{% endblock %} </style> @@ -34,6 +59,13 @@ </div> </div> </div> + <div id="spinnerOverlay" style="display: none;"> + <div class="d-flex align-items-center"> + <div class="spinner-border text-primary" role="status" aria-hidden="true"></div> + <span class="ml-3"><H5>设置中,需要重启线程,请稍候...</H5></span> + </div> + </div> + <main class="p-0 mb-0"> {% block content %}{% endblock %} </main> diff --git a/web/main/templates/channel_manager.html b/web/main/templates/channel_manager.html index 3a53261..38c4066 100644 --- a/web/main/templates/channel_manager.html +++ b/web/main/templates/channel_manager.html @@ -76,23 +76,21 @@ {% block content %} <div class="container d-flex flex-column" > - <div class="row mb-3 d-flex justify-content-center align-items-center "> - <div class="col"><h5 class="form-group-right">所属区域:</h5></div> - <div class="col-3 mr-2"> - <select id="areaSelect" class="form-select mr-2" aria-label="Default select example"> - <!-- 数据动态填充 --> - </select></div> - <div class="col"><h5 class="form-group-right">通道名称:</h5></div> - <div class="col-5 mr-2"> - <input id="channelNameInput" type="text" class="form-control mr-2" placeholder="Channel_name" aria-label="Channel_name"></div> - <div class="col-1"><button id="searchButton" type="button" class="btn btn-primary">查 询</button></div> - </div> + <div class="row justify-content-center align-items-center mb-3"> + <div class="col-md-2 text-end"><label class="col-form-label form-label">所属区域:</label></div> + <div class="col-md-3"> + <select id="areaSelect" class="form-select mr-2" aria-label="Default select example"></select></div> + <div class="col-md-2 text-end"><label class="col-form-label form-label">通道名称:</label></div> + <div class="col-md-3"><input id="channelNameInput" type="text" class="form-control"></div> + <div class="col-md-2"><button id="searchButton" type="button" class="btn btn-primary">查 询</button></div> + </div> + <div class="mb-3"> -<!-- <button id="manageAreaButton" type="button" class="btn btn-primary mr-2">区域管理</button>--> <button id="addChannelButton" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#channelModal"> 新增通道 </button> </div> + <!-- 新增通道模态框 --> <div class="modal fade" id="channelModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="add_channel" aria-hidden="true"> <div class="modal-dialog"> @@ -103,17 +101,17 @@ </div> <div class="modal-body"> <div class="form-group"> - <label for="areaSelect_M">所属区域:</label> + <label for="areaSelect_M" class="form-label">所属区域:</label> <select id="areaSelect_M" class="form-select" aria-label="D"> <!-- 数据动态填充 --> </select> </div> <div class="form-group"> - <label for="CNameInput">通道名称:</label> + <label for="CNameInput" class="form-label">通道名称:</label> <input type="text" class="form-control" id="CNameInput"> </div> <div class="form-group"> - <label for="RTSPInput">RTSP地址:</label> + <label for="RTSPInput" class="form-label">RTSP地址:</label> <input type="text" class="form-control" id="RTSPInput"> </div> </div> @@ -135,17 +133,17 @@ </div> <div class="modal-body"> <div class="form-group"> - <label for="areaSelect_CC">所属区域:</label> + <label for="areaSelect_CC" class="form-label">所属区域:</label> <select id="areaSelect_CC" class="form-select" aria-label="D"> <!-- 数据动态填充 --> </select> </div> <div class="form-group"> - <label for="CNameInput_cc">通道名称:</label> + <label for="CNameInput_cc" class="form-label">通道名称:</label> <input type="text" class="form-control" id="CNameInput_cc"> </div> <div class="form-group"> - <label for="RTSPInput_cc">RTSP地址:</label> + <label for="RTSPInput_cc" class="form-label">RTSP地址:</label> <input type="text" class="form-control" id="RTSPInput_cc"> </div> </div> @@ -229,7 +227,7 @@ </div> <!-- 布放计划 --> <div class="row form-group"> - <label for="11">布放计划:</label> + <label for="11">布防计划:</label> <div id="11"> <table class="schedule-table table table-sm table-bordered" style="font-size: 7px;"> <thead> diff --git a/web/main/templates/header.html b/web/main/templates/header.html index cf849ef..ae593d4 100644 --- a/web/main/templates/header.html +++ b/web/main/templates/header.html @@ -8,12 +8,12 @@ <span class="fs-4">ZF_BOX</span> </a> - <ul class="nav nav-pills"> + <ul class="nav nav-pills mr-2"> <li class="nav-item"><a href="/view_main.html" class="nav-link active" aria-current="page">实时预览</a></li> <li class="nav-item"><a href="/channel_manager.html" class="nav-link">通道管理</a></li> - <li class="nav-item"><a href="/schedule.html" class="nav-link">算法管理</a></li> - <li class="nav-item"><a href="#" class="nav-link">系统管理</a></li> - <li class="nav-item"><a href="#" class="nav-link">用户管理</a></li> + <li class="nav-item"><a href="/model_manager.html" class="nav-link">算法管理</a></li> + <li class="nav-item"><a href="/system_manager.html" class="nav-link">系统管理</a></li> + <li class="nav-item"><a href="/user_manager.html" class="nav-link">用户管理</a></li> </ul> <div class="dropdown text-end"> @@ -25,7 +25,7 @@ <!-- <img src="https://github.com/mdo.png" alt="mdo" width="32" height="32" class="rounded-circle">--> </a> <ul class="dropdown-menu text-small"> - <li><a class="dropdown-item" href="#">修改密码</a></li> + <li><a class="dropdown-item" href="/user_manager.html">修改密码</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">退 出</a></li> </ul> diff --git a/web/main/templates/model_manager.html b/web/main/templates/model_manager.html new file mode 100644 index 0000000..d1e6e86 --- /dev/null +++ b/web/main/templates/model_manager.html @@ -0,0 +1,145 @@ +{% extends 'base.html' %} + +{% block title %}ZFBOX{% endblock %} + +{% block style %} + .table-container { + min-height: 400px; /* 设置最小高度,可以根据需要调整 */ + } + /* 缩小表格行高 */ + .table-sm th, + .table-sm td { + padding: 0.2rem; /* 调整这里的值来改变行高 */ + } + .pagination { + justify-content: flex-end; /* 右对齐 */ + } + +{% endblock %} + +{% block content %} +<div class="container d-flex flex-column" > + <!-- 模态框区域 --> + <!-- 新增算法模态框 --> + <div class="modal fade" id="addMM" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="add_model" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title">新增算法</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <div class="form-group mb-2"> + <label for="MNameInput" class="form-label">算法名称:</label> + <input type="text" class="form-control" id="MNameInput"> + </div> + <div class="form-group mb-2"> + <label for="uploadModelFile" class="form-label">上传文件:</label> + <input type="file" class="form-control" id="uploadModelFile" accept=".zip"> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="cancelButton_model">取消</button> + <button type="button" class="btn btn-primary" id="saveButton_model">保存</button> + </div> + </div> + </div> + </div> + <!-- 升级算法模态框 --> + <div class="modal fade" id="updateMM" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="update_model" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title">升级算法</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <div class="form-group mb-3"> + <label id="update_mname_label" class="form-label">算法名称:</label> + </div> + <div class="form-group mb-3"> + <label id="update_mversion_label" class="form-label">当前版本:</label> + </div> + <div class="form-group mb-3"> + <label for="uploadModelFile" class="form-label">上传文件:</label> + <input type="file" class="form-control" id="updateModelFile" accept=".zip"> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="cancelButton_upmodel">取消</button> + <button type="button" class="btn btn-primary" id="saveButton_upmodel">保存</button> + </div> + </div> + </div> + </div> + <!-- 配置算法模态框 --> + <div class="modal fade" id="configMM" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="config_model" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title">配置算法</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <div class="form-group mb-3"> + <label id="config_mname_label" class="form-label">算法名称:</label> + </div> + <div class="form-group mb-3"> + <label for="duration_timeInput" class="form-label">持续判断时间(秒):</label> + <input type="text" class="form-control" id="duration_timeInput"> + </div> + <div class="form-group mb-3"> + <label for="proportionInput" class="form-label">占比阈值(0-1):</label> + <input type="text" class="form-control" id="proportionInput"> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="cancelButton_config_model">取消</button> + <button type="button" class="btn btn-primary" id="saveButton_config_model">保存</button> + </div> + </div> + </div> + </div> + <!-- 搜索区 --> + <div class="row justify-content-center align-items-center mb-3"> + <div class="col-md-2 text-end"><label class="col-form-label form-label">算法名称:</label></div> + <div class="col-md-6"><input id="modelNameInput" type="text" class="form-control"></div> + <div class="col-md-2"><button id="searchMButton" type="button" class="btn btn-primary">查 询</button></div> + </div> + <!-- 按钮区 --> + <div class="mb-3"> + <button id="addModelButton" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMM"> + 新增算法 + </button> + </div> + <!-- 表格区 --> + <div class="table-container"> + <table class="table"> + <thead class="table-light"> + <tr> + <th scope="col">ID</th> + <th scope="col">算法名称</th> + <th scope="col">版本号</th> + <th scope="col">持续判断时间</th> + <th scope="col">占比阈值</th> + <th scope="col">操作</th> + </tr> + </thead> + <tbody id="table-body-model" class="table-group-divider"> + <!-- 表格数据动态填充 --> + </tbody> + </table> + <nav> + <ul id="pagination-model" class="pagination"> + <!-- 分页控件将动态生成 --> + </ul> + </nav> + </div> + +</div> +{% endblock %} + +{% block script %} +<script src="{{ url_for('main.static', filename='scripts/model_manager.js') }}"></script> +<script src="{{ url_for('main.static', filename='scripts/jquery-3.2.1.slim.min.js') }}"></script> +{% endblock %} \ No newline at end of file diff --git a/web/main/templates/schedule.html b/web/main/templates/schedule.html deleted file mode 100644 index 4981582..0000000 --- a/web/main/templates/schedule.html +++ /dev/null @@ -1,156 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <title>布防时间计划</title> - <link rel="stylesheet" href="{{ url_for('main.static', filename='css/bootstrap.min.css') }}"> - <style> - .schedule-table { - width: 100%; - table-layout: fixed; - } - .schedule-table th, .schedule-table td { - text-align: center; - vertical-align: middle; - cursor: pointer; - border: 1px solid #dee2e6; - padding: 8px; - } - .schedule-table td.allowed { - background-color: white; - } - .schedule-table td.blocked { - background-color: blue; - } - </style> -</head> -<body> -<div class="container mt-5"> - <table class="schedule-table table table-bordered"> - <thead> - <tr> - <th>小时</th> - <th>00</th> - <th>01</th> - <th>02</th> - <th>03</th> - <th>04</th> - <th>05</th> - <th>06</th> - <th>07</th> - <th>08</th> - <th>09</th> - <th>10</th> - <th>11</th> - <th>12</th> - <th>13</th> - <th>14</th> - <th>15</th> - <th>16</th> - <th>17</th> - <th>18</th> - <th>19</th> - <th>20</th> - <th>21</th> - <th>22</th> - <th>23</th> - </tr> - </thead> - <tbody> - <!-- Repeat above row for each day of the week (Monday to Saturday) --> - <tr> - <th>星期一</th> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - <tr> - <th>星期二</th> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - <tr> - <th>星期三</th> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - <tr> - <th>星期四</th> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - <tr> - <th>星期五</th> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - <tr> - <th>星期六</th> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - <tr> - <th>星期日</th> - <!-- 24 cells for each hour --> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - <td class="blocked"></td><td class="blocked"></td><td class="blocked"></td><td class="blocked"></td> - </tr> - </tbody> - </table> - <div class="mt-3"> - <div class="d-inline-block mr-3"> - <div class="d-inline-block align-middle" style="width: 20px; height: 20px; background-color: white; border: 1px solid black;"></div> - <span class="align-middle">允许</span> - </div> - <div class="d-inline-block"> - <div class="d-inline-block align-middle" style="width: 20px; height: 20px; background-color: blue;"></div> - <span class="align-middle">阻止</span> - </div> - </div> -</div> -<script> - document.addEventListener('DOMContentLoaded', () => { - const cells = document.querySelectorAll('.schedule-table tbody td'); - cells.forEach(cell => { - cell.addEventListener('click', () => { - if (cell.classList.contains('blocked')) { - cell.classList.remove('blocked'); - cell.classList.add('allowed'); - } else { - cell.classList.remove('allowed'); - cell.classList.add('blocked'); - } - }); - }); - }); -</script> -</body> -</html> diff --git a/web/main/templates/system_manager.html b/web/main/templates/system_manager.html new file mode 100644 index 0000000..f6f36e2 --- /dev/null +++ b/web/main/templates/system_manager.html @@ -0,0 +1,286 @@ +{% extends 'base.html' %} + +{% block title %}ZFBOX{% endblock %} + +{% block style %} + .btn-blue { + background-color: #007bff; + color: white; + } + .btn-blue:hover { + background-color: #0056b3; + } + + .table-container { + min-height: 300px; /* 设置最小高度,可以根据需要调整 */ + } + /* 缩小表格行高 */ + .table-sm th, + .table-sm td { + padding: 0.2rem; /* 调整这里的值来改变行高 */ + } + .pagination { + justify-content: flex-end; /* 右对齐 */ + } + + .section-title { + position: relative; + margin: 20px 0; + } + .section-title hr { + margin: 0; + border-color: #000; /* You can change the color of the line if needed */ + } +{% endblock %} + +{% block content %} +<div class="container d-flex flex-column" > + <!-- 模态框区域 --> + <!-- 配置IP模态框--> + <div class="modal fade" id="ipConfigModal" tabindex="-1" aria-labelledby="ipConfigModalLabel" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title" id="ipConfigModalLabel">IP地址配置</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <!-- Tabs for Wired and Wireless IP --> + <ul class="nav nav-tabs" id="ipTab" role="tablist"> + <li class="nav-item" role="presentation"> + <button class="nav-link active" id="wired-tab" data-bs-toggle="tab" data-bs-target="#wired" type="button" role="tab" aria-controls="wired" aria-selected="true">有线IP</button> + </li> + <li class="nav-item" role="presentation"> + <button class="nav-link" id="wireless-tab" data-bs-toggle="tab" data-bs-target="#wireless" type="button" role="tab" aria-controls="wireless" aria-selected="false">无线IP</button> + </li> + </ul> + <!-- Tab content --> + <div class="tab-content mt-3" id="ipTabContent"> + <!-- Wired IP Configuration --> + <div class="tab-pane fade show active" id="wired" role="tabpanel" aria-labelledby="wired-tab"> + <div class="mb-3"> + <div class="row"> + <div class="col-6"> + <div class="form-check"> + <input class="form-check-input" type="radio" name="ip_lan" + id="dhcp_lan" checked onclick="handleRadioClick_lan(event)"> + <label class="form-check-label" for="dhcp_lan">自动获取</label> + </div> + </div> + <div class="col-6"> + <div class="form-check"> + <input class="form-check-input" type="radio" name="ip_lan" + id="static_lan" onclick="handleRadioClick_lan(event)"> + <label class="form-check-label" for="static_lan">静态IP</label> + </div> + </div> + </div> + </div> + <div class="mb-3"> + <label for="wiredIpAddress" class="form-label">有线IP地址</label> + <input type="text" class="form-control" id="wiredIpAddress" placeholder="例如: 192.168.1.2"> + </div> + <div class="mb-3"> + <label for="wiredSubnetMask" class="form-label">子网掩码</label> + <input type="text" class="form-control" id="wiredSubnetMask" placeholder="例如: 255.255.255.0"> + </div> + <div class="mb-3"> + <label for="wiredGateway" class="form-label">网关</label> + <input type="text" class="form-control" id="wiredGateway" placeholder="例如: 192.168.1.1"> + </div> + <div> + <label for="wirelessGateway" class="form-label">DNS</label> + <input type="text" class="form-control" id="wiredDNS" placeholder="例如: 114.114.114.114"> + </div> + </div> + <!-- Wireless IP Configuration --> + <div class="tab-pane fade" id="wireless" role="tabpanel" aria-labelledby="wireless-tab"> + <div class="mb-2"> + <label for="wirelessNetwork" class="form-label">选择无线网络</label> + <select class="form-select" id="wirelessNetwork"> + <!-- 数据动态填充 --> + </select> + </div> + <div class="mb-4"> + <div class="row justify-content-center align-items-center"> + <div class="col-2"><label for="wirelessSubnetMask" class="form-label">密码:</label></div> + <div class="col-8"><input type="password" class="form-control" id="wifi_passwd"></div> + <div class="col-2"><button type="button" class="btn btn-primary" id="connectWifi">连接</button></div> + </div> + </div> + <div class="mb-2"> + <div class="row"> + <div class="col-6"> + <div class="form-check"> + <input class="form-check-input" type="radio" name="ip_wifi" + id="dhcp_wifi" checked onclick="handleRadioClick_wifi(event)"> + <label class="form-check-label" for="dhcp_wifi">自动获取</label> + </div> + </div> + <div class="col-6"> + <div class="form-check"> + <input class="form-check-input" type="radio" name="ip_wifi" + id="static_wifi" onclick="handleRadioClick_wifi(event)"> + <label class="form-check-label" for="static_wifi">静态IP</label> + </div> + </div> + </div> + </div> + <div class="mb-2"> + <label for="wirelessIpAddress" class="form-label">无线IP地址</label> + <input type="text" class="form-control" id="wirelessIpAddress" placeholder="例如: 192.168.1.3"> + </div> + <div class="mb-2"> + <label for="wirelessSubnetMask" class="form-label">子网掩码</label> + <input type="text" class="form-control" id="wirelessSubnetMask" placeholder="例如: 255.255.255.0"> + </div> + <div class="mb-2"> + <label for="wirelessGateway" class="form-label">网关</label> + <input type="text" class="form-control" id="wirelessGateway" placeholder="例如: 192.168.1.1"> + </div> + <div> + <label for="wirelessGateway" class="form-label">DNS</label> + <input type="text" class="form-control" id="wirelessDNS" placeholder="例如: 114.114.114.114"> + </div> + </div> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> + <button type="button" class="btn btn-primary" id="saveIPConfig">保存设置</button> + </div> + </div> + </div> + </div> + <!-- 修改服务器IP模态框--> + <div class="modal fade" id="ServerIPModal" tabindex="-1" aria-labelledby="ServerIPModal" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title">服务器IP地址配置</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <div class="mb-3"> + <label for="serviceIP_model" class="form-label">服务器IP</label> + <input type="text" class="form-control" id="serviceIP_model" placeholder="例如: 127.0.0.1"> + </div> + <div class="mb-3"> + <label for="servicePort_model" class="form-label">端口号</label> + <input type="text" class="form-control" id="servicePort_model" placeholder="例如: 8085"> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> + <button type="button" class="btn btn-primary" id="saveServerIP">保存设置</button> + </div> + </div> + </div> + </div> + <!-- 新增区域模态框--> + <div class="modal fade" id="addAreaModal" tabindex="-1" aria-labelledby="AreaModal" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title" id="area_modal_title_id">新增区域</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <div class="mb-3"> + <label for="area_name" class="form-label">区域名称</label> + <input type="text" class="form-control" id="area_name"> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> + <button type="button" class="btn btn-primary" id="addArea">保存设置</button> + </div> + </div> + </div> + </div> + <!-- 修改区域模态框--> + <div class="modal fade" id="modifyAreaModal" tabindex="-1" aria-labelledby="AreaModal" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title">修改区域</h5> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <div class="mb-3"> + <label for="area_name" class="form-label">区域名称</label> + <input type="text" class="form-control" id="area_name_modif"> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> + <button type="button" class="btn btn-primary" id="modifArea">保存设置</button> + </div> + </div> + </div> + </div> + <!-- 系统信息区域 --> + <div class="container mt-4"> + <div class="row justify-content-center align-items-center"> + <div class="col-md-3 text-end"><label class="col-form-label form-label">系统版本号:</label></div> + <div class="col-md-9"><p class="form-control-plaintext" id="system_version">1.0.0.1</p></div> + </div> + <div class="row justify-content-center align-items-center"> + <div class="col-md-3 text-end"><label class="col-form-label form-label">升级包:</label></div> + <div class="col-md-6"><input type="file" class="form-control" id="upgrade-system"></div> + <div class="col-md-3"><button class="btn btn-blue" id="upsystem">升级</button></div> + </div> + <div class="row justify-content-center align-items-center"> + <div class="col-md-3 text-end"><label class="col-form-label form-label">设备ID:</label></div> + <div class="col-md-9"><p class="form-control-plaintext" id="dev_ID">1.0.0.1</p></div> + </div> + <div class="row justify-content-center align-items-center"> + <div class="col-md-3 text-end"><label class="col-form-label form-label">设备IP:</label></div> + <div class="col-md-6"><p class="form-control-plaintext" id="dev_IP"> + 有线--192.168.3.45 WIFI--192.168.3.45 5G--192.168.3.45</p></div> + <div class="col-md-3"><button class="btn btn-blue" id="showIPConfig">配置</button></div> + </div> + <div class="row justify-content-center align-items-center"> + <div class="col-md-3 text-end"><label class="col-form-label form-label">服务器IP:</label></div> + <div class="col-md-3"><input type="text" class="form-control" id="service_ip"></div> + <div class="col-md"><label class="col-form-label form-label">端口号:</label></div> + <div class="col-md"><input type="text" class="form-control" id="service_port"></div> + <div class="col-md-3"><button class="btn btn-blue" id="showServerIP">修改</button></div> + </div> + </div> + <!-- 区域管理区域 --> + <div class="section-title"> + <hr> + </div> + <div class="mb-3"> + <button id="addAreaButton" type="button" class="btn btn-primary"> + 新增区域 + </button> + </div> + <div class="table-container"> + <table class="table"> + <thead class="table-light"> + <tr> + <th scope="col" style="width: 20%;">ID</th> + <th scope="col" style="width: 50%;">区域名称</th> + <th scope="col" style="width: 30%;">操作</th> + </tr> + </thead> + <tbody id="table-body-area" class="table-group-divider"> + <!-- 表格数据动态填充 --> + </tbody> + </table> + <nav> + <ul id="pagination-area" class="pagination"> + <!-- 分页控件将动态生成 --> + </ul> + </nav> + </div> + +</div> +{% endblock %} + +{% block script %} +<script src="{{ url_for('main.static', filename='scripts/jquery-3.2.1.slim.min.js') }}"></script> +<script src="{{ url_for('main.static', filename='scripts/system_manager.js') }}"></script> +{% endblock %} \ No newline at end of file diff --git a/web/main/templates/user_manager.html b/web/main/templates/user_manager.html new file mode 100644 index 0000000..f70c0f4 --- /dev/null +++ b/web/main/templates/user_manager.html @@ -0,0 +1,48 @@ +{% extends 'base.html' %} + +{% block title %}ZFBOX{% endblock %} + +{% block style %} + .note { + color: red; + font-size: 0.9rem; + } + .btn-blue { + background-color: #007bff; + color: white; + } + .btn-blue:hover { + background-color: #0056b3; + } +{% endblock %} + +{% block content %} +<div class="container d-flex flex-column" > + <div class="row justify-content-center align-items-center mb-2"> + <div class="col-md-2 text-end"><label class="col-form-label form-label">用户名:</label></div> + <div class="col-md-7"><p class="form-control-plaintext" id="system_version">zfadmin</p></div> + </div> + <div class="row justify-content-center align-items-center mb-2"> + <div class="col-md-2 text-end"><label class="col-form-label form-label">原密码:</label></div> + <div class="col-md-7"><input type="password" class="form-control" id="source_passwd"></div> + </div> + <div class="row justify-content-center align-items-center mb-2"> + <div class="col-md-2 text-end"><label class="col-form-label form-label">新密码:</label></div> + <div class="col-md-7"><input type="password" class="form-control" id="new_passwd"></div> + </div> + <div class="row justify-content-center align-items-center mb-2"> + <div class="col-md-2 text-end"><label class="col-form-label form-label">确认密码:</label></div> + <div class="col-md-7"><input type="password" class="form-control" id="again_passwd"></div> + </div> + <div class="row justify-content-center align-items-center mb-2"> + <div class="col-md-6 text-end"></div> + <div class="col-md-3"><button class="btn btn-blue w-100" id="changePasswd">修改密码</button></div> + </div> + + +</div> +{% endblock %} + +{% block script %} +<script src="{{ url_for('main.static', filename='scripts/user_manager.js') }}"></script> +{% endblock %} \ No newline at end of file diff --git a/web/main/templates/实时预览.html b/web/main/templates/实时预览.html deleted file mode 100644 index a722556..0000000 --- a/web/main/templates/实时预览.html +++ /dev/null @@ -1,367 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <title>实时预览</title> - <meta http-equiv="X-UA-Compatible" content="IE=edge"/> - <meta http-equiv="content-type" content="text/html; charset=utf-8"/> - <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/> - <link href="data/styles.css" type="text/css" rel="stylesheet"/> - <link href="files/实时预览/styles.css" type="text/css" rel="stylesheet"/> - <script src="resources/scripts/jquery-3.2.1.min.js"></script> - <script src="resources/scripts/axure/axQuery.js"></script> - <script src="resources/scripts/axure/globals.js"></script> - <script src="resources/scripts/axutils.js"></script> - <script src="resources/scripts/axure/annotation.js"></script> - <script src="resources/scripts/axure/axQuery.std.js"></script> - <script src="resources/scripts/axure/doc.js"></script> - <script src="resources/scripts/messagecenter.js"></script> - <script src="resources/scripts/axure/events.js"></script> - <script src="resources/scripts/axure/recording.js"></script> - <script src="resources/scripts/axure/action.js"></script> - <script src="resources/scripts/axure/expr.js"></script> - <script src="resources/scripts/axure/geometry.js"></script> - <script src="resources/scripts/axure/flyout.js"></script> - <script src="resources/scripts/axure/model.js"></script> - <script src="resources/scripts/axure/repeater.js"></script> - <script src="resources/scripts/axure/sto.js"></script> - <script src="resources/scripts/axure/utils.temp.js"></script> - <script src="resources/scripts/axure/variables.js"></script> - <script src="resources/scripts/axure/drag.js"></script> - <script src="resources/scripts/axure/move.js"></script> - <script src="resources/scripts/axure/visibility.js"></script> - <script src="resources/scripts/axure/style.js"></script> - <script src="resources/scripts/axure/adaptive.js"></script> - <script src="resources/scripts/axure/tree.js"></script> - <script src="resources/scripts/axure/init.temp.js"></script> - <script src="resources/scripts/axure/legacy.js"></script> - <script src="resources/scripts/axure/viewer.js"></script> - <script src="resources/scripts/axure/math.js"></script> - <script src="resources/scripts/axure/jquery.nicescroll.min.js"></script> - <script src="data/document.js"></script> - <script src="files/实时预览/data.js"></script> - <script type="text/javascript"> - $axure.utils.getTransparentGifPath = function() { return 'resources/images/transparent.gif'; }; - $axure.utils.getOtherPath = function() { return 'resources/Other.html'; }; - $axure.utils.getReloadPath = function() { return 'resources/reload.html'; }; - </script> - </head> - <body> - <div id="base" class=""> - - <!-- Unnamed (web框架一) --> - - <!-- Unnamed (Rectangle) --> - <div id="u16" class="ax_default flow_shape"> - <div id="u16_div" class=""></div> - <div id="u16_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u17" class="ax_default flow_shape"> - <div id="u17_div" class=""></div> - <div id="u17_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u18" class="ax_default heading_1"> - <div id="u18_div" class=""></div> - <div id="u18_text" class="text "> - <p><span>智凡BOX</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u19" class="ax_default heading_3"> - <div id="u19_div" class=""></div> - <div id="u19_text" class="text "> - <p><span>@2024 ZFKJ All Rights Reserved </span></p> - </div> - </div> - - <!-- Unnamed (Menu) --> - <div id="u20" class="ax_default"> - <img id="u20_menu" class="img " src="images/实时预览/u20_menu.png" alt="u20_menu"/> - - <!-- Unnamed (Table) --> - <div id="u21" class="ax_default"> - - <!-- Unnamed (Menu Item) --> - <div id="u22" class="ax_default menu_item"> - <img id="u22_img" class="img " src="images/实时预览/u22.png"/> - <div id="u22_text" class="text "> - <p><span>实时预览</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u23" class="ax_default menu_item"> - <img id="u23_img" class="img " src="images/实时预览/u22.png"/> - <div id="u23_text" class="text "> - <p><span>通道管理</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u24" class="ax_default menu_item"> - <img id="u24_img" class="img " src="images/实时预览/u22.png"/> - <div id="u24_text" class="text "> - <p><span>算法管理</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u25" class="ax_default menu_item"> - <img id="u25_img" class="img " src="images/实时预览/u22.png"/> - <div id="u25_text" class="text "> - <p><span>系统管理</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u26" class="ax_default menu_item"> - <img id="u26_img" class="img " src="images/实时预览/u26.png"/> - <div id="u26_text" class="text "> - <p><span>用户管理</span></p> - </div> - </div> - </div> - </div> - - <!-- Unnamed (Shape) --> - <div id="u27" class="ax_default icon"> - <img id="u27_img" class="img " src="images/登录/u4.svg"/> - <div id="u27_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u28" class="ax_default heading_3"> - <div id="u28_div" class=""></div> - <div id="u28_text" class="text "> - <p><span>张三</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u29" class="ax_default primary_button"> - <div id="u29_div" class=""></div> - <div id="u29_text" class="text "> - <p><span>退出</span></p> - </div> - </div> - <div id="u15" style="display:none; visibility:hidden;"></div> - - <!-- Unnamed (Rectangle) --> - <div id="u30" class="ax_default primary_button"> - <div id="u30_div" class=""></div> - <div id="u30_text" class="text "> - <p><span>实时预览</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u31" class="ax_default flow_shape"> - <div id="u31_div" class=""></div> - <div id="u31_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <script src="/resources/scripts/aiortc-client-new.js"> - console.log('当指定了src属性时,浏览器会加载并执行该文件中的脚本,而忽略标签内部的任何内容,所以不会执行'); - </script> - - <!-- Unnamed (Image) --> - <div id="u32" class="ax_default image"> - <img id="u32_video" src="" alt="Video Stream"> - </div> - <!-- Unnamed (Image) --> - <div id="u33" class="ax_default image"> - <img id="u33_video" src="" alt="Video Stream"> - </div> - - - <!-- Unnamed (Image) --> - <div id="u34" class="ax_default image"> -<!-- <video id="u34_video" autoplay="true" playsinline="true"></video>--> - <img id="u34_video" src="" alt="Video Stream"> - </div> - - <!-- Unnamed (Image) --> - <div id="u35" class="ax_default image"> -<!-- <video id="u35_video" autoplay="true" playsinline="true"></video>--> - <img id="u35_video" src="" alt="Video Stream"> - </div> - - <!-- Unnamed (Image) --> - <div id="u36" class="ax_default image"> -<!-- <video id="u36_video" autoplay="true" playsinline="true"></video>--> - <img id="u36_video" src="" alt="Video Stream"> - </div> - - <!-- Unnamed (Image) --> - <div id="u37" class="ax_default image"> -<!-- <video id="u37_video" autoplay="true" playsinline="true"></video>--> - <img id="u37_video" src="" alt="Video Stream"> - </div> - - <!-- Unnamed (Image) --> - <div id="u38" class="ax_default image"> -<!-- <video id="u38_video" autoplay="true" playsinline="true"></video>--> - <img id="u38_video" src="" alt="Video Stream"> - </div> - - <!-- Unnamed (Image) --> - <div id="u39" class="ax_default image"> -<!-- <video id="u39_video" autoplay="true" playsinline="true"></video>--> - <img id="u39_video" src="" alt="Video Stream"> - </div> - - <!-- Unnamed (Image) --> - <div id="u40" class="ax_default image"> - <img id="u40_img" class="img " src="images/实时预览/u32.png"/> - <div id="u40_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u41" class="ax_default label"> - <div id="u41_div" class=""></div> - <div id="u41_text" class="text "> - <p><span><< 1/2 >></span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u42" class="ax_default button"> - <div id="u42_div" class=""></div> - <div id="u42_text" class="text "> - <p><span>一画面</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u43" class="ax_default button"> - <div id="u43_div" class=""></div> - <div id="u43_text" class="text "> - <p><span>四画面</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u44" class="ax_default button"> - <div id="u44_div" class=""></div> - <div id="u44_text" class="text "> - <p><span>九画面</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u45" class="ax_default button"> - <div id="u45_div" class=""></div> - <div id="u45_text" class="text "> - <p><span>十六<br>画面</span></p> - </div> - </div> - - <!-- Unnamed (Tree) --> - <div id="u46" class="ax_default tree_node treeroot"> - <div id="u46_children" class="u46_children"> - - <!-- Unnamed (Tree Node) --> - <div id="u47" class="ax_default tree_node treenode"> - - <!-- Unnamed (Image) --> - <div id="u48" class="ax_default image"> - <img id="u48_img" class="img " src="images/实时预览/u48_selected.png"/> - <div id="u48_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - <!-- Unnamed (Rectangle) --> - <div id="u49" class="" selectiongroup="u46_tree_group"> - <div id="u49_div" class=""></div> - <div id="u49_text" class="text "> - <p><span>一厂区</span></p> - </div> - </div> - <div id="u47_children" class="u47_children"> - - <!-- Unnamed (Tree Node) --> - <div id="u50" class="ax_default tree_node treenode"> - <!-- Unnamed (Rectangle) --> - <div id="u51" class="" selectiongroup="u46_tree_group"> - <div id="u51_div" class=""></div> - <div id="u51_text" class="text "> - <p><span>北门通道一</span></p> - </div> - </div> - </div> - - <!-- Unnamed (Tree Node) --> - <div id="u52" class="ax_default tree_node treenode"> - <!-- Unnamed (Rectangle) --> - <div id="u53" class="" selectiongroup="u46_tree_group"> - <div id="u53_div" class=""></div> - <div id="u53_text" class="text "> - <p><span>南门通道二</span></p> - </div> - </div> - </div> - - <!-- Unnamed (Tree Node) --> - <div id="u54" class="ax_default tree_node treenode"> - <!-- Unnamed (Rectangle) --> - <div id="u55" class="" selectiongroup="u46_tree_group"> - <div id="u55_div" class=""></div> - <div id="u55_text" class="text "> - <p><span>通道三</span></p> - </div> - </div> - </div> - </div> - </div> - - <!-- Unnamed (Tree Node) --> - <div id="u56" class="ax_default tree_node treenode"> - - <!-- Unnamed (Image) --> - <div id="u57" class="ax_default image"> - <img id="u57_img" class="img " src="images/实时预览/u48_selected.png"/> - <div id="u57_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - <!-- Unnamed (Rectangle) --> - <div id="u58" class="" selectiongroup="u46_tree_group"> - <div id="u58_div" class=""></div> - <div id="u58_text" class="text "> - <p><span>二区域</span></p> - </div> - </div> - <div id="u56_children" class="u56_children"> - - <!-- Unnamed (Tree Node) --> - <div id="u59" class="ax_default tree_node treenode"> - <!-- Unnamed (Rectangle) --> - <div id="u60" class="" selectiongroup="u46_tree_group"> - <div id="u60_div" class=""></div> - <div id="u60_text" class="text "> - <p><span>通道一</span></p> - </div> - </div> - </div> - </div> - </div> - </div> - </div> - </div> - <script src="resources/scripts/axure/ios.js"></script> - </body> -</html> diff --git a/web/main/templates/通道管理.html b/web/main/templates/通道管理.html deleted file mode 100644 index 659c131..0000000 --- a/web/main/templates/通道管理.html +++ /dev/null @@ -1,1412 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <title>通道管理</title> - <meta http-equiv="X-UA-Compatible" content="IE=edge"/> - <meta http-equiv="content-type" content="text/html; charset=utf-8"/> - <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/> - <link href="data/styles.css" type="text/css" rel="stylesheet"/> - <link href="files/通道管理/styles.css" type="text/css" rel="stylesheet"/> - <script src="resources/scripts/jquery-3.2.1.min.js"></script> - <script src="resources/scripts/axure/axQuery.js"></script> - <script src="resources/scripts/axure/globals.js"></script> - <script src="resources/scripts/axutils.js"></script> - <script src="resources/scripts/axure/annotation.js"></script> - <script src="resources/scripts/axure/axQuery.std.js"></script> - <script src="resources/scripts/axure/doc.js"></script> - <script src="resources/scripts/messagecenter.js"></script> - <script src="resources/scripts/axure/events.js"></script> - <script src="resources/scripts/axure/recording.js"></script> - <script src="resources/scripts/axure/action.js"></script> - <script src="resources/scripts/axure/expr.js"></script> - <script src="resources/scripts/axure/geometry.js"></script> - <script src="resources/scripts/axure/flyout.js"></script> - <script src="resources/scripts/axure/model.js"></script> - <script src="resources/scripts/axure/repeater.js"></script> - <script src="resources/scripts/axure/sto.js"></script> - <script src="resources/scripts/axure/utils.temp.js"></script> - <script src="resources/scripts/axure/variables.js"></script> - <script src="resources/scripts/axure/drag.js"></script> - <script src="resources/scripts/axure/move.js"></script> - <script src="resources/scripts/axure/visibility.js"></script> - <script src="resources/scripts/axure/style.js"></script> - <script src="resources/scripts/axure/adaptive.js"></script> - <script src="resources/scripts/axure/tree.js"></script> - <script src="resources/scripts/axure/init.temp.js"></script> - <script src="resources/scripts/axure/legacy.js"></script> - <script src="resources/scripts/axure/viewer.js"></script> - <script src="resources/scripts/axure/math.js"></script> - <script src="resources/scripts/axure/jquery.nicescroll.min.js"></script> - <script src="data/document.js"></script> - <script src="files/通道管理/data.js"></script> - <script type="text/javascript"> - $axure.utils.getTransparentGifPath = function() { return 'resources/images/transparent.gif'; }; - $axure.utils.getOtherPath = function() { return 'resources/Other.html'; }; - $axure.utils.getReloadPath = function() { return 'resources/reload.html'; }; - </script> - </head> - <body> - <div id="base" class=""> - - <!-- Unnamed (web框架一) --> - - <!-- Unnamed (Rectangle) --> - <div id="u62" class="ax_default flow_shape"> - <div id="u62_div" class=""></div> - <div id="u62_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u63" class="ax_default flow_shape"> - <div id="u63_div" class=""></div> - <div id="u63_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u64" class="ax_default heading_1"> - <div id="u64_div" class=""></div> - <div id="u64_text" class="text "> - <p><span>智凡BOX</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u65" class="ax_default heading_3"> - <div id="u65_div" class=""></div> - <div id="u65_text" class="text "> - <p><span>@2024 ZFKJ All Rights Reserved </span></p> - </div> - </div> - - <!-- Unnamed (Menu) --> - <div id="u66" class="ax_default"> - <img id="u66_menu" class="img " src="images/实时预览/u20_menu.png" alt="u66_menu"/> - - <!-- Unnamed (Table) --> - <div id="u67" class="ax_default"> - - <!-- Unnamed (Menu Item) --> - <div id="u68" class="ax_default menu_item"> - <img id="u68_img" class="img " src="images/实时预览/u22.png"/> - <div id="u68_text" class="text "> - <p><span>实时预览</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u69" class="ax_default menu_item"> - <img id="u69_img" class="img " src="images/实时预览/u22.png"/> - <div id="u69_text" class="text "> - <p><span>通道管理</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u70" class="ax_default menu_item"> - <img id="u70_img" class="img " src="images/实时预览/u22.png"/> - <div id="u70_text" class="text "> - <p><span>算法管理</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u71" class="ax_default menu_item"> - <img id="u71_img" class="img " src="images/实时预览/u22.png"/> - <div id="u71_text" class="text "> - <p><span>系统管理</span></p> - </div> - </div> - - <!-- Unnamed (Menu Item) --> - <div id="u72" class="ax_default menu_item"> - <img id="u72_img" class="img " src="images/实时预览/u26.png"/> - <div id="u72_text" class="text "> - <p><span>用户管理</span></p> - </div> - </div> - </div> - </div> - - <!-- Unnamed (Shape) --> - <div id="u73" class="ax_default icon"> - <img id="u73_img" class="img " src="images/登录/u4.svg"/> - <div id="u73_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u74" class="ax_default heading_3"> - <div id="u74_div" class=""></div> - <div id="u74_text" class="text "> - <p><span>张三</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u75" class="ax_default primary_button"> - <div id="u75_div" class=""></div> - <div id="u75_text" class="text "> - <p><span>退出</span></p> - </div> - </div> - <div id="u61" style="display:none; visibility:hidden;"></div> - - <!-- Unnamed (Rectangle) --> - <div id="u76" class="ax_default primary_button"> - <div id="u76_div" class=""></div> - <div id="u76_text" class="text "> - <p><span>通道管理</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u77" class="ax_default heading_2"> - <div id="u77_div" class=""></div> - <div id="u77_text" class="text "> - <p><span>所属区域:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u78" class="ax_default text_field"> - <div id="u78_div" class=""></div> - <input id="u78_input" type="text" value="" class="u78_input"/> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u79" class="ax_default primary_button"> - <div id="u79_div" class=""></div> - <div id="u79_text" class="text "> - <p><span>新增</span></p> - </div> - </div> - - <!-- Unnamed (Table) --> - <div id="u80" class="ax_default"> - - <!-- Unnamed (Table Cell) --> - <div id="u81" class="ax_default table_cell"> - <img id="u81_img" class="img " src="images/通道管理/u81.png"/> - <div id="u81_text" class="text "> - <p><span>序号</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u82" class="ax_default table_cell"> - <img id="u82_img" class="img " src="images/通道管理/u82.png"/> - <div id="u82_text" class="text "> - <p><span>所属区域</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u83" class="ax_default table_cell"> - <img id="u83_img" class="img " src="images/通道管理/u83.png"/> - <div id="u83_text" class="text "> - <p><span>通道名称</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u84" class="ax_default table_cell"> - <img id="u84_img" class="img " src="images/通道管理/u84.png"/> - <div id="u84_text" class="text "> - <p><span>RTSP地址</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u85" class="ax_default table_cell"> - <img id="u85_img" class="img " src="images/通道管理/u85.png"/> - <div id="u85_text" class="text "> - <p><span>拉流状态</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u86" class="ax_default table_cell"> - <img id="u86_img" class="img " src="images/通道管理/u86.png"/> - <div id="u86_text" class="text "> - <p><span>配置算法</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u87" class="ax_default table_cell"> - <img id="u87_img" class="img " src="images/通道管理/u87.png"/> - <div id="u87_text" class="text "> - <p><span>操作</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u88" class="ax_default table_cell"> - <img id="u88_img" class="img " src="images/通道管理/u81.png"/> - <div id="u88_text" class="text "> - <p><span>1</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u89" class="ax_default table_cell"> - <img id="u89_img" class="img " src="images/通道管理/u82.png"/> - <div id="u89_text" class="text "> - <p><span>厂区一</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u90" class="ax_default table_cell"> - <img id="u90_img" class="img " src="images/通道管理/u83.png"/> - <div id="u90_text" class="text "> - <p><span>北门一</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u91" class="ax_default table_cell"> - <img id="u91_img" class="img " src="images/通道管理/u84.png"/> - <div id="u91_text" class="text "> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u92" class="ax_default table_cell"> - <img id="u92_img" class="img " src="images/通道管理/u85.png"/> - <div id="u92_text" class="text "> - <p><span>在线</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u93" class="ax_default table_cell"> - <img id="u93_img" class="img " src="images/通道管理/u86.png"/> - <div id="u93_text" class="text "> - <p><span>无</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u94" class="ax_default table_cell"> - <img id="u94_img" class="img " src="images/通道管理/u87.png"/> - <div id="u94_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u95" class="ax_default table_cell"> - <img id="u95_img" class="img " src="images/通道管理/u81.png"/> - <div id="u95_text" class="text "> - <p><span>2</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u96" class="ax_default table_cell"> - <img id="u96_img" class="img " src="images/通道管理/u82.png"/> - <div id="u96_text" class="text "> - <p><span>厂区一</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u97" class="ax_default table_cell"> - <img id="u97_img" class="img " src="images/通道管理/u83.png"/> - <div id="u97_text" class="text "> - <p><span>北门二</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u98" class="ax_default table_cell"> - <img id="u98_img" class="img " src="images/通道管理/u84.png"/> - <div id="u98_text" class="text "> - <p><span>rtsp://www.easydarwin.org:554/your_stream_id</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u99" class="ax_default table_cell"> - <img id="u99_img" class="img " src="images/通道管理/u85.png"/> - <div id="u99_text" class="text "> - <p><span>0</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u100" class="ax_default table_cell"> - <img id="u100_img" class="img " src="images/通道管理/u86.png"/> - <div id="u100_text" class="text "> - <p><span>人员入侵,安全帽</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u101" class="ax_default table_cell"> - <img id="u101_img" class="img " src="images/通道管理/u87.png"/> - <div id="u101_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u102" class="ax_default table_cell"> - <img id="u102_img" class="img " src="images/通道管理/u81.png"/> - <div id="u102_text" class="text "> - <p><span>3</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u103" class="ax_default table_cell"> - <img id="u103_img" class="img " src="images/通道管理/u82.png"/> - <div id="u103_text" class="text "> - <p><span>厂区二</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u104" class="ax_default table_cell"> - <img id="u104_img" class="img " src="images/通道管理/u83.png"/> - <div id="u104_text" class="text "> - <p><span>南门一</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u105" class="ax_default table_cell"> - <img id="u105_img" class="img " src="images/通道管理/u84.png"/> - <div id="u105_text" class="text "> - <p><span>rtsp://www.easydarwin.org:554/your_stream_id</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u106" class="ax_default table_cell"> - <img id="u106_img" class="img " src="images/通道管理/u85.png"/> - <div id="u106_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u107" class="ax_default table_cell"> - <img id="u107_img" class="img " src="images/通道管理/u86.png"/> - <div id="u107_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u108" class="ax_default table_cell"> - <img id="u108_img" class="img " src="images/通道管理/u87.png"/> - <div id="u108_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u109" class="ax_default table_cell"> - <img id="u109_img" class="img " src="images/通道管理/u81.png"/> - <div id="u109_text" class="text "> - <p><span>4</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u110" class="ax_default table_cell"> - <img id="u110_img" class="img " src="images/通道管理/u82.png"/> - <div id="u110_text" class="text "> - <p><span>厂区二</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u111" class="ax_default table_cell"> - <img id="u111_img" class="img " src="images/通道管理/u83.png"/> - <div id="u111_text" class="text "> - <p><span>南门二</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u112" class="ax_default table_cell"> - <img id="u112_img" class="img " src="images/通道管理/u84.png"/> - <div id="u112_text" class="text "> - <p><span>rtsp://www.easydarwin.org:554/your_stream_id</span></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u113" class="ax_default table_cell"> - <img id="u113_img" class="img " src="images/通道管理/u85.png"/> - <div id="u113_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u114" class="ax_default table_cell"> - <img id="u114_img" class="img " src="images/通道管理/u86.png"/> - <div id="u114_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u115" class="ax_default table_cell"> - <img id="u115_img" class="img " src="images/通道管理/u87.png"/> - <div id="u115_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u116" class="ax_default table_cell"> - <img id="u116_img" class="img " src="images/通道管理/u81.png"/> - <div id="u116_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u117" class="ax_default table_cell"> - <img id="u117_img" class="img " src="images/通道管理/u82.png"/> - <div id="u117_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u118" class="ax_default table_cell"> - <img id="u118_img" class="img " src="images/通道管理/u83.png"/> - <div id="u118_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u119" class="ax_default table_cell"> - <img id="u119_img" class="img " src="images/通道管理/u84.png"/> - <div id="u119_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u120" class="ax_default table_cell"> - <img id="u120_img" class="img " src="images/通道管理/u85.png"/> - <div id="u120_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u121" class="ax_default table_cell"> - <img id="u121_img" class="img " src="images/通道管理/u86.png"/> - <div id="u121_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u122" class="ax_default table_cell"> - <img id="u122_img" class="img " src="images/通道管理/u87.png"/> - <div id="u122_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u123" class="ax_default table_cell"> - <img id="u123_img" class="img " src="images/通道管理/u81.png"/> - <div id="u123_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u124" class="ax_default table_cell"> - <img id="u124_img" class="img " src="images/通道管理/u82.png"/> - <div id="u124_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u125" class="ax_default table_cell"> - <img id="u125_img" class="img " src="images/通道管理/u83.png"/> - <div id="u125_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u126" class="ax_default table_cell"> - <img id="u126_img" class="img " src="images/通道管理/u84.png"/> - <div id="u126_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u127" class="ax_default table_cell"> - <img id="u127_img" class="img " src="images/通道管理/u85.png"/> - <div id="u127_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u128" class="ax_default table_cell"> - <img id="u128_img" class="img " src="images/通道管理/u86.png"/> - <div id="u128_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u129" class="ax_default table_cell"> - <img id="u129_img" class="img " src="images/通道管理/u87.png"/> - <div id="u129_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u130" class="ax_default table_cell"> - <img id="u130_img" class="img " src="images/通道管理/u81.png"/> - <div id="u130_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u131" class="ax_default table_cell"> - <img id="u131_img" class="img " src="images/通道管理/u82.png"/> - <div id="u131_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u132" class="ax_default table_cell"> - <img id="u132_img" class="img " src="images/通道管理/u83.png"/> - <div id="u132_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u133" class="ax_default table_cell"> - <img id="u133_img" class="img " src="images/通道管理/u84.png"/> - <div id="u133_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u134" class="ax_default table_cell"> - <img id="u134_img" class="img " src="images/通道管理/u85.png"/> - <div id="u134_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u135" class="ax_default table_cell"> - <img id="u135_img" class="img " src="images/通道管理/u86.png"/> - <div id="u135_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u136" class="ax_default table_cell"> - <img id="u136_img" class="img " src="images/通道管理/u87.png"/> - <div id="u136_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u137" class="ax_default table_cell"> - <img id="u137_img" class="img " src="images/通道管理/u81.png"/> - <div id="u137_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u138" class="ax_default table_cell"> - <img id="u138_img" class="img " src="images/通道管理/u82.png"/> - <div id="u138_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u139" class="ax_default table_cell"> - <img id="u139_img" class="img " src="images/通道管理/u83.png"/> - <div id="u139_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u140" class="ax_default table_cell"> - <img id="u140_img" class="img " src="images/通道管理/u84.png"/> - <div id="u140_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u141" class="ax_default table_cell"> - <img id="u141_img" class="img " src="images/通道管理/u85.png"/> - <div id="u141_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u142" class="ax_default table_cell"> - <img id="u142_img" class="img " src="images/通道管理/u86.png"/> - <div id="u142_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u143" class="ax_default table_cell"> - <img id="u143_img" class="img " src="images/通道管理/u87.png"/> - <div id="u143_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u144" class="ax_default table_cell"> - <img id="u144_img" class="img " src="images/通道管理/u81.png"/> - <div id="u144_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u145" class="ax_default table_cell"> - <img id="u145_img" class="img " src="images/通道管理/u82.png"/> - <div id="u145_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u146" class="ax_default table_cell"> - <img id="u146_img" class="img " src="images/通道管理/u83.png"/> - <div id="u146_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u147" class="ax_default table_cell"> - <img id="u147_img" class="img " src="images/通道管理/u84.png"/> - <div id="u147_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u148" class="ax_default table_cell"> - <img id="u148_img" class="img " src="images/通道管理/u85.png"/> - <div id="u148_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u149" class="ax_default table_cell"> - <img id="u149_img" class="img " src="images/通道管理/u86.png"/> - <div id="u149_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u150" class="ax_default table_cell"> - <img id="u150_img" class="img " src="images/通道管理/u87.png"/> - <div id="u150_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u151" class="ax_default table_cell"> - <img id="u151_img" class="img " src="images/通道管理/u81.png"/> - <div id="u151_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u152" class="ax_default table_cell"> - <img id="u152_img" class="img " src="images/通道管理/u82.png"/> - <div id="u152_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u153" class="ax_default table_cell"> - <img id="u153_img" class="img " src="images/通道管理/u83.png"/> - <div id="u153_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u154" class="ax_default table_cell"> - <img id="u154_img" class="img " src="images/通道管理/u84.png"/> - <div id="u154_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u155" class="ax_default table_cell"> - <img id="u155_img" class="img " src="images/通道管理/u85.png"/> - <div id="u155_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u156" class="ax_default table_cell"> - <img id="u156_img" class="img " src="images/通道管理/u86.png"/> - <div id="u156_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u157" class="ax_default table_cell"> - <img id="u157_img" class="img " src="images/通道管理/u87.png"/> - <div id="u157_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u158" class="ax_default table_cell"> - <img id="u158_img" class="img " src="images/通道管理/u81.png"/> - <div id="u158_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u159" class="ax_default table_cell"> - <img id="u159_img" class="img " src="images/通道管理/u82.png"/> - <div id="u159_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u160" class="ax_default table_cell"> - <img id="u160_img" class="img " src="images/通道管理/u83.png"/> - <div id="u160_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u161" class="ax_default table_cell"> - <img id="u161_img" class="img " src="images/通道管理/u84.png"/> - <div id="u161_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u162" class="ax_default table_cell"> - <img id="u162_img" class="img " src="images/通道管理/u85.png"/> - <div id="u162_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u163" class="ax_default table_cell"> - <img id="u163_img" class="img " src="images/通道管理/u86.png"/> - <div id="u163_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u164" class="ax_default table_cell"> - <img id="u164_img" class="img " src="images/通道管理/u87.png"/> - <div id="u164_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u165" class="ax_default table_cell"> - <img id="u165_img" class="img " src="images/通道管理/u81.png"/> - <div id="u165_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u166" class="ax_default table_cell"> - <img id="u166_img" class="img " src="images/通道管理/u82.png"/> - <div id="u166_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u167" class="ax_default table_cell"> - <img id="u167_img" class="img " src="images/通道管理/u83.png"/> - <div id="u167_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u168" class="ax_default table_cell"> - <img id="u168_img" class="img " src="images/通道管理/u84.png"/> - <div id="u168_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u169" class="ax_default table_cell"> - <img id="u169_img" class="img " src="images/通道管理/u85.png"/> - <div id="u169_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u170" class="ax_default table_cell"> - <img id="u170_img" class="img " src="images/通道管理/u86.png"/> - <div id="u170_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u171" class="ax_default table_cell"> - <img id="u171_img" class="img " src="images/通道管理/u87.png"/> - <div id="u171_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u172" class="ax_default table_cell"> - <img id="u172_img" class="img " src="images/通道管理/u81.png"/> - <div id="u172_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u173" class="ax_default table_cell"> - <img id="u173_img" class="img " src="images/通道管理/u82.png"/> - <div id="u173_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u174" class="ax_default table_cell"> - <img id="u174_img" class="img " src="images/通道管理/u83.png"/> - <div id="u174_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u175" class="ax_default table_cell"> - <img id="u175_img" class="img " src="images/通道管理/u84.png"/> - <div id="u175_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u176" class="ax_default table_cell"> - <img id="u176_img" class="img " src="images/通道管理/u85.png"/> - <div id="u176_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u177" class="ax_default table_cell"> - <img id="u177_img" class="img " src="images/通道管理/u86.png"/> - <div id="u177_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u178" class="ax_default table_cell"> - <img id="u178_img" class="img " src="images/通道管理/u87.png"/> - <div id="u178_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u179" class="ax_default table_cell"> - <img id="u179_img" class="img " src="images/通道管理/u179.png"/> - <div id="u179_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u180" class="ax_default table_cell"> - <img id="u180_img" class="img " src="images/通道管理/u180.png"/> - <div id="u180_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u181" class="ax_default table_cell"> - <img id="u181_img" class="img " src="images/通道管理/u181.png"/> - <div id="u181_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u182" class="ax_default table_cell"> - <img id="u182_img" class="img " src="images/通道管理/u182.png"/> - <div id="u182_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u183" class="ax_default table_cell"> - <img id="u183_img" class="img " src="images/通道管理/u183.png"/> - <div id="u183_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u184" class="ax_default table_cell"> - <img id="u184_img" class="img " src="images/通道管理/u184.png"/> - <div id="u184_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Table Cell) --> - <div id="u185" class="ax_default table_cell"> - <img id="u185_img" class="img " src="images/通道管理/u185.png"/> - <div id="u185_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - </div> - - <!-- Unnamed (Shape) --> - <div id="u186" class="ax_default button"> - <img id="u186_img" class="img " src="images/通道管理/u186.svg"/> - <div id="u186_text" class="text "> - <p><span>算法</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u187" class="ax_default button"> - <div id="u187_div" class=""></div> - <div id="u187_text" class="text "> - <p><span>修改</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u188" class="ax_default button"> - <div id="u188_div" class=""></div> - <div id="u188_text" class="text "> - <p><span>删除</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u189" class="ax_default label"> - <div id="u189_div" class=""></div> - <div id="u189_text" class="text "> - <p><span><< 1/2 >></span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u190" class="ax_default button"> - <div id="u190_div" class=""></div> - <div id="u190_text" class="text "> - <p><span>算法</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u191" class="ax_default button"> - <div id="u191_div" class=""></div> - <div id="u191_text" class="text "> - <p><span>修改</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u192" class="ax_default button"> - <div id="u192_div" class=""></div> - <div id="u192_text" class="text "> - <p><span>删除</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u193" class="ax_default button"> - <div id="u193_div" class=""></div> - <div id="u193_text" class="text "> - <p><span>查询</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u194" class="ax_default heading_2"> - <div id="u194_div" class=""></div> - <div id="u194_text" class="text "> - <p><span>通道名称:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u195" class="ax_default text_field"> - <div id="u195_div" class=""></div> - <input id="u195_input" type="text" value="" class="u195_input"/> - </div> - - <!-- 新增通道 (Dynamic Panel) --> - <div id="u196" class="ax_default ax_default_hidden" data-label="新增通道" style="display:none; visibility: hidden"> - <div id="u196_state0" class="panel_state" data-label="State1" style=""> - <div id="u196_state0_content" class="panel_state_content"> - - <!-- Unnamed (Rectangle) --> - <div id="u197" class="ax_default flow_shape"> - <div id="u197_div" class=""></div> - <div id="u197_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u198" class="ax_default heading_2"> - <div id="u198_div" class=""></div> - <div id="u198_text" class="text "> - <p><span>新增</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u199" class="ax_default primary_button"> - <div id="u199_div" class=""></div> - <div id="u199_text" class="text "> - <p><span>取消</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u200" class="ax_default primary_button"> - <div id="u200_div" class=""></div> - <div id="u200_text" class="text "> - <p><span>确认</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u201" class="ax_default heading_3"> - <div id="u201_div" class=""></div> - <div id="u201_text" class="text "> - <p><span>所属区域:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u202" class="ax_default text_field"> - <div id="u202_div" class=""></div> - <input id="u202_input" type="text" value="" class="u202_input"/> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u203" class="ax_default heading_3"> - <div id="u203_div" class=""></div> - <div id="u203_text" class="text "> - <p><span>通道名称:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u204" class="ax_default text_field"> - <div id="u204_div" class=""></div> - <input id="u204_input" type="text" value="" class="u204_input"/> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u205" class="ax_default heading_3"> - <div id="u205_div" class=""></div> - <div id="u205_text" class="text "> - <p><span>RTSP地址:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u206" class="ax_default text_field"> - <div id="u206_div" class=""></div> - <input id="u206_input" type="text" value="" class="u206_input"/> - </div> - - <!-- Unnamed (Shape) --> - <div id="u207" class="ax_default button"> - <img id="u207_img" class="img " src="images/通道管理/u207.svg"/> - <div id="u207_text" class="text "> - <p><span>测试拉流</span></p> - </div> - </div> - </div> - </div> - </div> - - <!-- 配置算法 (Dynamic Panel) --> - <div id="u208" class="ax_default ax_default_hidden" data-label="配置算法" style="display:none; visibility: hidden"> - <div id="u208_state0" class="panel_state" data-label="State1" style=""> - <div id="u208_state0_content" class="panel_state_content"> - - <!-- Unnamed (Rectangle) --> - <div id="u209" class="ax_default flow_shape"> - <div id="u209_div" class=""></div> - <div id="u209_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u210" class="ax_default heading_2"> - <div id="u210_div" class=""></div> - <div id="u210_text" class="text "> - <p><span>配置算法</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u211" class="ax_default primary_button"> - <div id="u211_div" class=""></div> - <div id="u211_text" class="text "> - <p><span>取消</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u212" class="ax_default primary_button"> - <div id="u212_div" class=""></div> - <div id="u212_text" class="text "> - <p><span>确认</span></p> - </div> - </div> - - <!-- Unnamed (Image) --> - <div id="u213" class="ax_default image"> - <img id="u213_img" class="img " src="images/通道管理/u213.svg"/> - <div id="u213_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Droplist) --> - <div id="u214" class="ax_default droplist"> - <div id="u214_div" class=""></div> - <select id="u214_input" class="u214_input"> - <option class="u214_input_option" value="人员入侵">人员入侵</option> - <option class="u214_input_option" value="安全帽检测">安全帽检测</option> - <option class="u214_input_option" value="工服检测">工服检测</option> - </select> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u215" class="ax_default heading_2"> - <div id="u215_div" class=""></div> - <div id="u215_text" class="text "> - <p><span>选择算法:</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u216" class="ax_default heading_2"> - <div id="u216_div" class=""></div> - <div id="u216_text" class="text "> - <p><span>检测区域:</span></p> - </div> - </div> - - <!-- Unnamed (Radio Button) --> - <div id="u217" class="ax_default radio_button"> - <label id="u217_input_label" for="u217_input" style="position: absolute; left: 0px;"> - <img id="u217_img" class="img " src="images/通道管理/u217.svg"/> - <div id="u217_text" class="text "> - <p><span>全画面生效</span></p> - </div> - </label> - <input id="u217_input" type="radio" value="radio" name="u217"/> - </div> - - <!-- Unnamed (Radio Button) --> - <div id="u218" class="ax_default radio_button"> - <label id="u218_input_label" for="u218_input" style="position: absolute; left: 0px;"> - <img id="u218_img" class="img " src="images/通道管理/u218.svg"/> - <div id="u218_text" class="text "> - <p><span>指定区域</span></p> - </div> - </label> - <input id="u218_input" type="radio" value="radio" name="u218"/> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u219" class="ax_default button"> - <div id="u219_div" class=""></div> - <div id="u219_text" class="text "> - <p><span>绘制区域</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u220" class="ax_default heading_2"> - <div id="u220_div" class=""></div> - <div id="u220_text" class="text "> - <p><span>检测时间:</span></p> - </div> - </div> - - <!-- Unnamed (Image) --> - <div id="u221" class="ax_default image"> - <img id="u221_img" class="img " src="images/通道管理/u221.png"/> - <div id="u221_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - </div> - </div> - </div> - - <!-- 修改 (Dynamic Panel) --> - <div id="u222" class="ax_default ax_default_hidden" data-label="修改" style="display:none; visibility: hidden"> - <div id="u222_state0" class="panel_state" data-label="State1" style=""> - <div id="u222_state0_content" class="panel_state_content"> - - <!-- Unnamed (Rectangle) --> - <div id="u223" class="ax_default flow_shape"> - <div id="u223_div" class=""></div> - <div id="u223_text" class="text " style="display:none; visibility: hidden"> - <p></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u224" class="ax_default heading_2"> - <div id="u224_div" class=""></div> - <div id="u224_text" class="text "> - <p><span>修改</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u225" class="ax_default primary_button"> - <div id="u225_div" class=""></div> - <div id="u225_text" class="text "> - <p><span>取消</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u226" class="ax_default primary_button"> - <div id="u226_div" class=""></div> - <div id="u226_text" class="text "> - <p><span>确认</span></p> - </div> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u227" class="ax_default heading_3"> - <div id="u227_div" class=""></div> - <div id="u227_text" class="text "> - <p><span>所属区域:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u228" class="ax_default text_field"> - <div id="u228_div" class=""></div> - <input id="u228_input" type="text" value="厂区一" class="u228_input"/> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u229" class="ax_default heading_3"> - <div id="u229_div" class=""></div> - <div id="u229_text" class="text "> - <p><span>通道名称:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u230" class="ax_default text_field"> - <div id="u230_div" class=""></div> - <input id="u230_input" type="text" value="北门一" class="u230_input"/> - </div> - - <!-- Unnamed (Rectangle) --> - <div id="u231" class="ax_default heading_3"> - <div id="u231_div" class=""></div> - <div id="u231_text" class="text "> - <p><span>RTSP地址:</span></p> - </div> - </div> - - <!-- Unnamed (Text Field) --> - <div id="u232" class="ax_default text_field"> - <div id="u232_div" class=""></div> - <input id="u232_input" type="text" value="RTSP" class="u232_input"/> - </div> - - <!-- Unnamed (Shape) --> - <div id="u233" class="ax_default button"> - <img id="u233_img" class="img " src="images/通道管理/u207.svg"/> - <div id="u233_text" class="text "> - <p><span>测试拉流</span></p> - </div> - </div> - </div> - </div> - </div> - </div> - <script src="resources/scripts/axure/ios.js"></script> - </body> -</html> diff --git a/zfbox.db b/zfbox.db index bc33ca8..91ed369 100644 Binary files a/zfbox.db and b/zfbox.db differ