From 2df88d8717c31a4626e85dcf95b5347da969c82c Mon Sep 17 00:00:00 2001 From: yangjian Date: Sat, 21 Mar 2020 16:11:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=9B=BE=E7=89=87=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=8A=9F=E8=83=BD=E3=80=81=E4=BC=98=E5=8C=96=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E3=80=81=E4=BF=AE=E5=A4=8D=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGES.md | 11 + MrDoc/settings.py | 5 +- README.md | 36 +- app_doc/migrations/0011_auto_20200313_2143.py | 52 + app_doc/migrations/0012_auto_20200313_2204.py | 19 + app_doc/migrations/0013_image_file_name.py | 18 + app_doc/models.py | 27 +- app_doc/templatetags/project_filter.py | 8 + app_doc/urls.py | 3 + app_doc/util_upload_img.py | 50 +- app_doc/views.py | 207 +- static/mrdoc-admin.css | 58 + static/mrdoc.css | 2 +- static/viewerjs/viewer.css | 456 +++ static/viewerjs/viewer.js | 3117 +++++++++++++++++ template/404.html | 3 - template/app_doc/create_base.html | 220 +- template/app_doc/doc.html | 33 +- template/app_doc/docs_base.html | 27 +- template/app_doc/manage_base.html | 9 +- template/app_doc/manage_image.html | 221 ++ template/app_doc/manage_image_group.html | 114 + 22 files changed, 4593 insertions(+), 103 deletions(-) create mode 100644 app_doc/migrations/0011_auto_20200313_2143.py create mode 100644 app_doc/migrations/0012_auto_20200313_2204.py create mode 100644 app_doc/migrations/0013_image_file_name.py create mode 100644 static/mrdoc-admin.css create mode 100644 static/viewerjs/viewer.css create mode 100644 static/viewerjs/viewer.js create mode 100644 template/app_doc/manage_image.html create mode 100644 template/app_doc/manage_image_group.html diff --git a/CHANGES.md b/CHANGES.md index d905205..e90b403 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,16 @@ ## 版本更新记录 +### v0.3.3 + +- 修复后台管理无法删除文档的错误; +- 修复后台新建无法新建文集的错误; +- 优化图片上传逻辑,新增后台图片管理功能,前端编辑器替换Editor.md自带的图片上传组件; +- 优化首页无文集时的样式,添加默认显示的图片; +- 优化首页文集无文档时,显示默认提示文字; +- 优化404页面,更换统一风格的404图片; +- 调整文档阅读页面目录使用悬浮弹出框显示; +- 增强安全性,替换前端请求字符串值中的特殊符号; + ### v0.3.2 2020-03-12 - 修复访问码跳转文档404的错误; diff --git a/MrDoc/settings.py b/MrDoc/settings.py index 4e52c72..6fee6ca 100644 --- a/MrDoc/settings.py +++ b/MrDoc/settings.py @@ -25,7 +25,7 @@ SECRET_KEY = '5&71mt9@^58zdg*_!t(x6g14q*@84d%ptr%%s6e0l50zs0we3d' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False -VERSIONS = '0.3.2' +VERSIONS = '0.3.3' ALLOWED_HOSTS = ['*'] @@ -85,6 +85,9 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + 'OPTIONS':{ + 'timeout':20, + } } } diff --git a/README.md b/README.md index 5510ba3..b730a32 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# MrDoc - 记录文档,汇聚思想,一个简单的文档记录和阅读应用 +# MrDoc - 记录文档,汇聚思想,一个简单的文档记录和管理应用 **PC端文档阅读界面:** @@ -6,11 +6,20 @@ ## 介绍 -州的先生(https://zmister.com)自用并完全开源、基于Python编写的文档写作系统。 +州的先生 - https://zmister.com - 自用并完全开源、基于Python编写的文档写作系统。 -当前版本为:**v0.3.2**,版本发布时间为**2020-03-12**,此版本主要更新了如下内容: +使用MarkDown快速记录你所思所想,仿GitBook两栏式阅读界面,清晰高效浏览。 -- 紧急修复访问码跳转文档404的错误; +当前版本为:**v0.3.3**,版本发布时间为**2020-03-21**,此版本主要更新了如下内容: + +- 修复后台管理无法删除文档的错误; +- 修复后台新建无法新建文集的错误; +- 优化图片上传逻辑,新增后台图片管理功能,前端编辑器替换Editor.md自带的图片上传组件,支持上传图片和从已有图片中选择图片; +- 优化首页无文集时的样式,添加默认显示的图片; +- 优化首页文集无文档时,显示默认提示文字; +- 优化404页面,更换统一风格的404图片; +- 调整文档阅读页面目录使用悬浮弹出框显示; +- 增强安全性,替换前端请求字符串值中的特殊符号; 完整更新记录详见:[CHANGES.md](./CHANGES.md) @@ -31,23 +40,14 @@ MrDoc拥有以下特点: - 支持三级目录层级显示; - 支持文集后台导出为markdown文本格式.md文件、前台导出为EPUB电子书; - 基于文集进行权限控制,提供公开、私密、指定用户可见、访问码可见4种权限模式; - -- 二次开发方便 - - 使用Django传统的MTV开发模式,路由、视图函数、模型易于理解; - - 使用非前端工程化构建前端页面,主要使用Layui进行页面布局和展示,方便改动; -在开发过程中,参考和借鉴了GitBook、ShowDoc、Wordbook等应用和网站的功能与样式。 +在开发过程中,参考和借鉴了GitBook、ShowDoc、Wordbook等应用和网站的功能与样式,并使用了众多开源组件、插件。 -## 网站架构 +## 应用核心依赖环境 -- 编程语言:Python 3 -- 后端Web框架:Django 2.1 -- 前端UI库:Layui 2.5.4 -- JS库:Jquery -- MarkDown编辑器:Editormd -- 页面社交分享:Share.js -- Markdown科学公式:Katex.js +- 编程语言:Python 3+ +- Django框架:2.0+ ## 安装教程 @@ -128,7 +128,7 @@ python manage.py runserver ## 版本更新 -关注州的先生微信公众号(ID:zmister2016)、博客 https://zmister.com,及时获取MrDoc版本更新信息。 +关注州的先生微信公众号(ID:zmister2016)、博客 https://zmister.com 及时获取MrDoc版本更新信息。 ## 更多截图 diff --git a/app_doc/migrations/0011_auto_20200313_2143.py b/app_doc/migrations/0011_auto_20200313_2143.py new file mode 100644 index 0000000..ca61564 --- /dev/null +++ b/app_doc/migrations/0011_auto_20200313_2143.py @@ -0,0 +1,52 @@ +# Generated by Django 2.1 on 2020-03-13 21:43 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('app_doc', '0010_auto_20200310_2032'), + ] + + operations = [ + migrations.CreateModel( + name='Image', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('file_path', models.CharField(max_length=250, verbose_name='图片路径')), + ('remark', models.CharField(blank=True, default='图片描述', max_length=250, null=True, verbose_name='图片备注')), + ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('modify_time', models.DateTimeField(auto_now=True, verbose_name='修改时间')), + ], + options={ + 'verbose_name': '素材图片', + 'verbose_name_plural': '素材图片', + }, + ), + migrations.CreateModel( + name='ImageGroup', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('group_name', models.CharField(default='默认分组', max_length=50, verbose_name='图片分组')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': '图片分组', + 'verbose_name_plural': '图片分组', + }, + ), + migrations.AddField( + model_name='image', + name='group', + field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.SET_DEFAULT, to='app_doc.ImageGroup', verbose_name='图片分组'), + ), + migrations.AddField( + model_name='image', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/app_doc/migrations/0012_auto_20200313_2204.py b/app_doc/migrations/0012_auto_20200313_2204.py new file mode 100644 index 0000000..9565c0f --- /dev/null +++ b/app_doc/migrations/0012_auto_20200313_2204.py @@ -0,0 +1,19 @@ +# Generated by Django 2.1 on 2020-03-13 22:04 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('app_doc', '0011_auto_20200313_2143'), + ] + + operations = [ + migrations.AlterField( + model_name='image', + name='group', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='app_doc.ImageGroup', verbose_name='图片分组'), + ), + ] diff --git a/app_doc/migrations/0013_image_file_name.py b/app_doc/migrations/0013_image_file_name.py new file mode 100644 index 0000000..496b6c2 --- /dev/null +++ b/app_doc/migrations/0013_image_file_name.py @@ -0,0 +1,18 @@ +# Generated by Django 2.1 on 2020-03-15 08:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('app_doc', '0012_auto_20200313_2204'), + ] + + operations = [ + migrations.AddField( + model_name='image', + name='file_name', + field=models.CharField(blank=True, max_length=250, null=True, verbose_name='图片名称'), + ), + ] diff --git a/app_doc/models.py b/app_doc/models.py index 54df757..5b7023d 100644 --- a/app_doc/models.py +++ b/app_doc/models.py @@ -71,7 +71,6 @@ class DocTemp(models.Model): verbose_name = '文档模板' verbose_name_plural = verbose_name - # 文集导出模型 class ProjectReport(models.Model): project = models.OneToOneField(Project,unique=True,on_delete=models.CASCADE) @@ -83,4 +82,30 @@ class ProjectReport(models.Model): class Meta: verbose_name = '文集导出' + verbose_name_plural = verbose_name + +# 图片分组模型 +class ImageGroup(models.Model): + user = models.ForeignKey(User,on_delete=models.CASCADE) + group_name = models.CharField(verbose_name="图片分组",max_length=50,default="默认分组") + + def __str__(self): + return self.group_name + + class Meta: + verbose_name = '图片分组' + verbose_name_plural = verbose_name + +# 图片模型 +class Image(models.Model): + user = models.ForeignKey(User,on_delete=models.CASCADE) + file_path = models.CharField(verbose_name="图片路径",max_length=250) + file_name = models.CharField(verbose_name="图片名称",max_length=250,null=True,blank=True) + group = models.ForeignKey(ImageGroup,on_delete=models.SET_NULL,null=True,verbose_name="图片分组") + remark = models.CharField(verbose_name="图片备注",null=True,blank=True,max_length=250,default="图片描述") + create_time = models.DateTimeField(verbose_name='创建时间',auto_now_add=True) + modify_time = models.DateTimeField(verbose_name='修改时间',auto_now=True) + + class Meta: + verbose_name = '素材图片' verbose_name_plural = verbose_name \ No newline at end of file diff --git a/app_doc/templatetags/project_filter.py b/app_doc/templatetags/project_filter.py index 0f28b30..95fd7c3 100644 --- a/app_doc/templatetags/project_filter.py +++ b/app_doc/templatetags/project_filter.py @@ -15,6 +15,8 @@ def get_doc_count(value): @register.filter(name='get_new_doc') def get_new_doc(value): new_doc = Doc.objects.filter(top_doc=int(value),status=1).order_by('-modify_time').first() + if new_doc is None: + new_doc = '它还没有文档……' return new_doc # 获取文集的开放导出状态 @@ -27,3 +29,9 @@ def get_report_status(value): # print(repr(e)) status = 0 return status + +# 获取图片分组的图片数量 +@register.filter(name='img_group_cnt') +def get_img_group_cnt(value): + cnt = Image.objects.filter(group_id=value).count() + return cnt \ No newline at end of file diff --git a/app_doc/urls.py b/app_doc/urls.py index 7581b43..0a827b1 100644 --- a/app_doc/urls.py +++ b/app_doc/urls.py @@ -27,6 +27,9 @@ urlpatterns = [ path('get_doctemp/',views.get_doctemp,name='get_doctemp'), # 获取某一个文档模板内容 path('del_doctemp/',views.del_doctemp,name="del_doctemp"), # 删除某一个文档模板 path('modify_doctemp//',views.modify_doctemp,name="modify_doctemp"), # 修改文档模板 + #################文件管理相关 + path('manage_image/',views.manage_image,name="manage_image"), # 图片管理 + path('manage_image_group/',views.manage_img_group,name="manage_img_group"), # 图片分组管理 ################其他功能相关 path('upload_doc_img/',util_upload_img.upload_img,name="upload_doc_img"), # 上传图片 ] \ No newline at end of file diff --git a/app_doc/util_upload_img.py b/app_doc/util_upload_img.py index 383d44c..b4cb952 100644 --- a/app_doc/util_upload_img.py +++ b/app_doc/util_upload_img.py @@ -2,48 +2,52 @@ from django.http import HttpResponse from django.conf import settings from django.views.decorators.csrf import csrf_exempt -import os -import uuid -import json -import datetime as dt -import base64 +from django.contrib.auth.decorators import login_required # 登录需求装饰器 +import datetime,time,json,base64,os,uuid +from app_doc.models import Image,ImageGroup +@login_required() @csrf_exempt def upload_img(request): ################## # {"success": 0, "message": "出错信息"} # {"success": 1, "url": "图片地址"} ################## - files = request.FILES.get("editormd-image-file", None) + img = request.FILES.get("editormd-image-file", None) # 编辑器上传 + manage_upload = request.FILES.get('manage_upload',None) # 图片管理上传 dir_name = request.POST.get('dirname','') base_img = request.POST.get('base',None) - if files:# 上传普通图片文件 - result = file_upload(files, dir_name) + if img:# 上传普通图片文件 + result = img_upload(img, dir_name,request.user) + elif manage_upload: + result = img_upload(manage_upload, dir_name, request.user) elif base_img: # 上传base64编码图片 - result = base_img_upload(base_img,dir_name) + result = base_img_upload(base_img,dir_name,request.user) else: result = {"success": 0, "message": "出错信息"} return HttpResponse(json.dumps(result), content_type="application/json") # 目录创建 def upload_generation_dir(dir_name=''): - today = dt.datetime.today() + today = datetime.datetime.today() dir_name = dir_name + '/%d%02d/' %(today.year,today.month) - print("dir_name:",dir_name) + # print("dir_name:",dir_name) if not os.path.exists(settings.MEDIA_ROOT + dir_name): - print("创建目录") + # print("创建目录") os.makedirs(settings.MEDIA_ROOT + dir_name) return dir_name # 普通图片上传 -def file_upload(files, dir_name): +def img_upload(files, dir_name, user): #允许上传文件类型 allow_suffix =["jpg", "jpeg", "gif", "png", "bmp", "webp"] - file_suffix = files.name.split(".")[-1] + file_suffix = files.name.split(".")[-1] # 提取图片格式 + # 判断图片格式 if file_suffix not in allow_suffix: return {"success": 0, "message": "图片格式不正确"} + relative_path = upload_generation_dir(dir_name) - file_name = str(dt.datetime.today()).replace(':','').replace(' ','').replace('.','')+files.name + file_name = files.name.replace(file_suffix,'').replace('.','') + '_' +str(int(time.time())) + '.' + file_suffix path_file=os.path.join(relative_path, file_name) path_file = settings.MEDIA_ROOT + path_file print('文件路径:',path_file) @@ -52,14 +56,20 @@ def file_upload(files, dir_name): with open(path_file, 'wb') as f: for chunk in files.chunks(): f.write(chunk) # 保存文件 + Image.objects.create( + user=user, + file_path=file_url, + file_name=file_name, + remark='本地上传', + ) return {"success": 1, "url": file_url,'message':'上传图片成功'} # base64编码图片上传 -def base_img_upload(files,dir_name): +def base_img_upload(files,dir_name, user): files_str = files.split(';base64,')[-1] # 截取图片正文 files_base = base64.b64decode(files_str) # 进行base64编码 relative_path = upload_generation_dir(dir_name) - file_name = str(dt.datetime.today()).replace(':', '').replace(' ', '').replace('.', '') + '.png' + file_name = str(datetime.datetime.today()).replace(':', '').replace(' ', '_').split('.')[0] + '.png' # 日期时间 path_file = os.path.join(relative_path, file_name) path_file = settings.MEDIA_ROOT + path_file print('文件路径:', path_file) @@ -67,4 +77,10 @@ def base_img_upload(files,dir_name): print("文件URL:", file_url) with open(path_file, 'wb') as f: f.write(files_base) # 保存文件 + Image.objects.create( + user = user, + file_path = file_url, + file_name=file_name, + remark = '粘贴上传', + ) return {"success": 1, "url": file_url, 'message': '上传图片成功'} \ No newline at end of file diff --git a/app_doc/views.py b/app_doc/views.py index 1a36ca7..6bbb5b2 100644 --- a/app_doc/views.py +++ b/app_doc/views.py @@ -11,9 +11,16 @@ from django.contrib.auth.models import User from django.db.models import Q import datetime import traceback +import re from app_doc.report_utils import * from app_admin.decorators import check_headers,allow_report_file +import os.path +# 替换前端传来的非法字符 +def validateTitle(title): + rstr = r"[\/\\\:\*\?\"\<\>\|]" # '/ \ : * ? " < > |' + new_title = re.sub(rstr, "_", title) # 替换为下划线 + return new_title # 文集列表 def project_list(request): @@ -34,23 +41,27 @@ def create_project(request): if request.method == 'POST': try: name = request.POST.get('pname','') + name = validateTitle(name) desc = request.POST.get('desc','') - role = request.POST.get('role','') + role = request.POST.get('role',0) + role_list = ['0','1','2','3',0,1,2,3] if name != '': project = Project.objects.create( name=name, intro=desc[:100], create_user=request.user, - role = int(role) + role = int(role) if role in role_list else 0 ) project.save() return JsonResponse({'status':True,'data':{'id':project.id,'name':project.name}}) else: - return JsonResponse({'status':False}) + return JsonResponse({'status':False,'data':'文集名称不能为空!'}) except Exception as e: - return JsonResponse({'status':False}) + if settings.DEBUG: + print(traceback.print_exc()) + return JsonResponse({'status':False,'data':'出现异常,请检查输入值!'}) else: - return JsonResponse({'status':False}) + return JsonResponse({'status':False,'data':'请求方法不允许'}) # 文集页 @@ -100,7 +111,6 @@ def project_index(request,pro_id): except Exception as e: if settings.DEBUG: print(traceback.print_exc()) - print(repr(e)) return HttpResponse('请求出错') @@ -121,6 +131,8 @@ def modify_project(request): else: return JsonResponse({'status':False,'data':'非法请求'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) else: return JsonResponse({'status':False,'data':'方法不允许'}) @@ -186,7 +198,8 @@ def check_viewcode(request): errormsg = "访问码错误" return render(request, 'app_doc/check_viewcode.html', locals()) except Exception as e: - print(repr(e)) + if settings.DEBUG: + print(traceback.print_exc()) return render(request,'404.html') @@ -209,6 +222,8 @@ def del_project(request): else: return JsonResponse({'status':False,'data':'参数错误'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) @@ -241,6 +256,8 @@ def manage_project(request): pros = paginator.page(paginator.num_pages) return render(request,'app_doc/manage_project.html',locals()) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return HttpResponse('请求出错') else: return HttpResponse('方法不允许') @@ -314,6 +331,8 @@ def doc(request,pro_id,doc_id): else: return HttpResponse('参数错误') except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return HttpResponse('请求出错') @@ -328,7 +347,8 @@ def create_doc(request): doctemp_list = DocTemp.objects.filter(create_user=request.user).values('id','name','create_time') return render(request,'app_doc/create_doc.html',locals()) except Exception as e: - print(repr(e)) + if settings.DEBUG: + print(traceback.print_exc()) return HttpResponse('请求出错') elif request.method == 'POST': try: @@ -354,7 +374,8 @@ def create_doc(request): else: return JsonResponse({'status':False,'data':'参数错误'}) except Exception as e: - print(repr(e)) + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) else: return JsonResponse({'status':False,'data':'方法不允许'}) @@ -374,6 +395,8 @@ def modify_doc(request,doc_id): else: return HttpResponse("非法请求") except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return HttpResponse('请求出错') elif request.method == 'POST': try: @@ -400,6 +423,8 @@ def modify_doc(request,doc_id): else: return JsonResponse({'status': False,'data':'参数错误'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) @@ -426,6 +451,8 @@ def del_doc(request): else: return JsonResponse({'status':False,'data':'参数错误'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) @@ -544,6 +571,8 @@ def create_doctemp(request): else: return JsonResponse({'status':False,'data':'模板标题不能为空'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) else: return JsonResponse({'status':False,'data':'方法不允许'}) @@ -560,6 +589,8 @@ def modify_doctemp(request,doctemp_id): else: return HttpResponse('非法请求') except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return HttpResponse('请求出错') elif request.method == 'POST': try: @@ -578,6 +609,8 @@ def modify_doctemp(request,doctemp_id): else: return JsonResponse({'status':False,'data':'参数错误'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) else: return HttpResponse('方法不允许') @@ -598,6 +631,8 @@ def del_doctemp(request): else: return JsonResponse({'status': False, 'data': '参数错误'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) @@ -630,6 +665,8 @@ def manage_doctemp(request): doctemps = paginator.page(paginator.num_pages) return render(request, 'app_doc/manage_doctemp.html', locals()) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return HttpResponse('请求出错') else: return HttpResponse('方法不允许') @@ -647,6 +684,8 @@ def get_doctemp(request): else: return JsonResponse({'status':False,'data':'参数错误'}) except Exception as e: + if settings.DEBUG: + print(traceback.print_exc()) return JsonResponse({'status':False,'data':'请求出错'}) else: return JsonResponse({'status':False,'data':'方法错误'}) @@ -758,4 +797,152 @@ def report_file(request): else: return JsonResponse({'status':False,'data':'不支持的类型'}) else: - return Http404 \ No newline at end of file + return Http404 + + +# 图片素材管理 +@login_required() +def manage_image(request): + # 获取图片 + if request.method == 'GET': + try: + groups = ImageGroup.objects.filter(user=request.user) # 获取所有分组 + all_img_cnt = Image.objects.filter(user=request.user).count() + no_group_cnt = Image.objects.filter(user=request.user,group_id=None).count() # 获取所有未分组的图片数量 + g_id = int(request.GET.get('group', 0)) # 图片分组id + if int(g_id) == 0: + image_list = Image.objects.filter(user=request.user) # 查询所有图片 + elif int(g_id) == -1: + image_list = Image.objects.filter(user=request.user,group_id=None) # 查询指定分组的图片 + else: + image_list = Image.objects.filter(user=request.user,group_id=g_id) # 查询指定分组的图片 + paginator = Paginator(image_list, 20) + page = request.GET.get('page', 1) + try: + images = paginator.page(page) + except PageNotAnInteger: + images = paginator.page(1) + except EmptyPage: + images = paginator.page(paginator.num_pages) + images.group = g_id + return render(request,'app_doc/manage_image.html',locals()) + except: + if settings.DEBUG: + print(traceback.print_exc()) + return render(request,'404.html') + elif request.method == 'POST': + try: + img_id = request.POST.get('img_id','') + types = request.POST.get('types','') # 操作类型:0表示删除,1表示修改,2表示获取 + # 删除图片 + if int(types) == 0: + img = Image.objects.get(id=img_id) + if img.user != request.user: + return JsonResponse({'status': False, 'data': '未授权请求'}) + file_path = settings.BASE_DIR+img.file_path + is_exist = os.path.exists(file_path) + if is_exist: + os.remove(file_path) + img.delete() # 删除记录 + return JsonResponse({'status':True,'data':'删除完成'}) + # 移动图片分组 + elif int(types) == 1: + group_id = request.POST.get('group_id',None) + if group_id is None: + Image.objects.filter(id=img_id).update(group_id=None) + else: + group = ImageGroup.objects.get(id=group_id,user=request.user) + Image.objects.filter(id=img_id).update(group_id=group) + return JsonResponse({'status':True,'data':'移动完成'}) + # 获取图片 + elif int(types) == 2: + group_id = request.POST.get('group_id', None) # 接受分组ID参数 + if group_id is None: # + return JsonResponse({'status':False,'data':'参数错误'}) + elif int(group_id) == 0: + imgs = Image.objects.filter(user=request.user) + elif int(group_id) == -1: + imgs = Image.objects.filter(user=request.user,group_id=None) + else: + imgs = Image.objects.filter(user=request.user,group_id=group_id) + img_list = [] + for img in imgs: + item = { + 'path':img.file_path, + 'name':img.file_name, + } + img_list.append(item) + return JsonResponse({'status':True,'data':img_list}) + else: + return JsonResponse({'status':False,'data':'非法参数'}) + except ObjectDoesNotExist: + return JsonResponse({'status':False,'data':'图片不存在'}) + except: + if settings.DEBUG: + print(traceback.print_exc()) + return JsonResponse({'status':False,'data':'程序异常'}) + +# 图片分组管理 +@login_required() +def manage_img_group(request): + if request.method == 'GET': + groups = ImageGroup.objects.filter(user=request.user) + return render(request,'app_doc/manage_image_group.html',locals()) + # 操作分组 + elif request.method == 'POST': + types = request.POST.get('types',None) # 请求类型,0表示创建分组,1表示修改分组,2表示删除分组,3表示获取分组 + # 创建分组 + if int(types) == 0: + group_name = request.POST.get('group_name', '') + if group_name not in ['','默认分组','未分组']: + ImageGroup.objects.create( + user = request.user, + group_name = group_name + ) + return JsonResponse({'status':True,'data':'ok'}) + else: + return JsonResponse({'status':False,'data':'名称无效'}) + # 修改分组 + elif int(types) == 1: + group_name = request.POST.get("group_name",'') + if group_name not in ['','默认分组','未分组']: + group_id = request.POST.get('group_id', '') + ImageGroup.objects.filter(id=group_id).update(group_name=group_name) + return JsonResponse({'status':True,'data':'修改成功'}) + else: + return JsonResponse({'status':False,'data':'名称无效'}) + + # 删除分组 + elif int(types) == 2: + try: + group_id = request.POST.get('group_id','') + group = ImageGroup.objects.get(id=group_id,user=request.user) # 查询分组 + images = Image.objects.filter(group_id=group_id).update(group_id=None) # 移动图片到未分组 + group.delete() # 删除分组 + return JsonResponse({'status':True,'data':'删除完成'}) + except: + if settings.DEBUG: + print(traceback.print_exc()) + return JsonResponse({'status':False,'data':'删除错误'}) + # 获取分组 + elif int(types) == 3: + try: + group_list = [] + all_cnt = Image.objects.all().count() + non_group_cnt = Image.objects.filter(group_id=None).count() + group_list.append({'group_name':'全部图片','group_cnt':all_cnt,'group_id':0}) + group_list.append({'group_name':'未分组','group_cnt':non_group_cnt,'group_id':-1}) + groups = ImageGroup.objects.filter(user=request.user) # 查询所有分组 + for group in groups: + group_cnt = Image.objects.filter(group_id=group).count() + item = { + 'group_id':group.id, + 'group_name':group.group_name, + 'group_cnt':group_cnt + } + group_list.append(item) + return JsonResponse({'status':True,'data':group_list}) + except: + if settings.DEBUG: + print(traceback.print_exc()) + return JsonResponse({'status':False,'data':'出现错误'}) \ No newline at end of file diff --git a/static/mrdoc-admin.css b/static/mrdoc-admin.css new file mode 100644 index 0000000..0bb1a86 --- /dev/null +++ b/static/mrdoc-admin.css @@ -0,0 +1,58 @@ +/* 用户中心 图片管理 */ +.image-list{ + cursor: pointer; + position: relative; + display:flex; + float: left; + align-items:center; + width: 160px; + height:180px; + margin: 0 20px 30px 0; + text-align: center; + overflow: hidden; +} + +.image-list:hover{ + background-color: #EAFFEA; +} +.image-list-i{ + display: block; + width: 100%; + height: auto; + -webkit-background-size: contain; + /*background-size: contain;*/ + /*background-position: 50% 50%;*/ + /*background-repeat: no-repeat;*/ + /*padding-bottom: 100%;*/ + border: 1px solid transparent; + border-radius: 3px; + overflow: hidden; +} + +.img-file-name{ + overflow: hidden; + text-overflow: ellipsis; + -o-text-overflow: ellipsis; + white-space:nowrap; + width:160px; + height:24px; + display:block; +} +/* 图片管理按钮 */ +.opera-img-btn{ + position: absolute; + top: 0px; + right: 0px; + width: 160px; + height: 25px; + display: none; + background:#393D49; + opacity:0.5; +} +.opera-img-btn i{ + font-size:20px; + color:white; +} +.opera-img-btn i:hover{ + color:red; +} \ No newline at end of file diff --git a/static/mrdoc.css b/static/mrdoc.css index 8af793a..178f548 100644 --- a/static/mrdoc.css +++ b/static/mrdoc.css @@ -198,7 +198,7 @@ body, html { min-width: 0; background: #fff; flex-direction: column; - padding-bottom: 64px; + /*padding-bottom: 64px;*/ -webkit-box-orient: vertical; -webkit-box-direction: normal; left:300px; diff --git a/static/viewerjs/viewer.css b/static/viewerjs/viewer.css new file mode 100644 index 0000000..2ff2181 --- /dev/null +++ b/static/viewerjs/viewer.css @@ -0,0 +1,456 @@ +/*! + * Viewer.js v1.5.0 + * https://fengyuanchen.github.io/viewerjs + * + * Copyright 2015-present Chen Fengyuan + * Released under the MIT license + * + * Date: 2019-11-23T05:10:21.757Z + */ + +.viewer-zoom-in::before, +.viewer-zoom-out::before, +.viewer-one-to-one::before, +.viewer-reset::before, +.viewer-prev::before, +.viewer-play::before, +.viewer-next::before, +.viewer-rotate-left::before, +.viewer-rotate-right::before, +.viewer-flip-horizontal::before, +.viewer-flip-vertical::before, +.viewer-fullscreen::before, +.viewer-fullscreen-exit::before, +.viewer-close::before { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARgAAAAUCAYAAABWOyJDAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAQPSURBVHic7Zs/iFxVFMa/0U2UaJGksUgnIVhYxVhpjDbZCBmLdAYECxsRFBTUamcXUiSNncgKQbSxsxH8gzAP3FU2jY0kKKJNiiiIghFlccnP4p3nPCdv3p9778vsLOcHB2bfveeb7955c3jvvNkBIMdxnD64a94GHMfZu3iBcRynN7zAOI7TG15gHCeeNUkr8zaxG2lbYDYsdgMbktBsP03jdQwljSXdtBhLOmtjowC9Mg9L+knSlcD8TNKpSA9lBpK2JF2VdDSR5n5J64m0qli399hNFMUlpshQii5jbXTbHGviB0nLNeNDSd9VO4A2UdB2fp+x0eCnaXxWXGA2X0au/3HgN9P4LFCjIANOJdrLr0zzZ+BEpNYDwKbpnQMeAw4m8HjQtM6Z9qa917zPQwFr3M5KgA6J5rTJCdFZJj9/lyvGhsDvwFNVuV2MhhjrK6b9bFiE+j1r87eBl4HDwCF7/U/k+ofAX5b/EXBv5JoLMuILzf3Ap6Z3EzgdqHMCuF7hcQf4HDgeoHnccncqdK/TvSDWffFXI/exICY/xZyqc6XLWF1UFZna4gJ7q8BsRvgd2/xXpo6P+D9dfT7PpECtA3cnWPM0GXGFZh/wgWltA+cDNC7X+AP4GzjZQe+k5dRxuYPeiuXU7e1qwLpDz7dFjXKRaSwuMLvAlG8zZlG+YmiK1HoFqT7wP2z+4Q45TfEGcMt01xLoNZEBTwRqD4BLpnMLeC1A41UmVxsXgXeBayV/Wx20rpTyrpnWRft7p6O/FdqzGrDukPNtkaMoMo3FBdBSQMOnYBCReyf05s126fU9ytfX98+mY54Kxnp7S9K3kj6U9KYdG0h6UdLbkh7poFXMfUnSOyVvL0h6VtIXHbS6nOP+s/Zm9mvyXW1uuC9ohZ72E9uDmXWLJOB1GxsH+DxPftsB8B6wlGDN02TAkxG6+4D3TWsbeC5CS8CDFce+AW500LhhOW2020TRjK3b21HEmgti9m0RonxbdMZeVzV+/4tF3cBpP7E9mKHNL5q8h5g0eYsCMQz0epq8gQrwMXAgcs0FGXGFRcB9wCemF9PkbYqM/Bas7fxLwNeJPdTdpo4itQti8lPMqTpXuozVRVXPpbHI3KkNTB1NfkL81j2mvhDp91HgV9MKuRIqrykj3WPq4rHyL+axj8/qGPmTqi6F9YDlHOvJU6oYcTsh/TYSzWmTE6JT19CtLTJt32D6CmHe0eQn1O8z5AXgT4sx4Vcu0/EQecMydB8z0hUWkTd2t4CrwNEePqMBcAR4mrBbwyXLPWJa8zrXmmLEhNBmfpkuY2102xxrih+pb+ieAb6vGhuA97UcJ5KR8gZ77K+99xxeYBzH6Q3/Z0fHcXrDC4zjOL3hBcZxnN74F+zlvXFWXF9PAAAAAElFTkSuQmCC'); + background-repeat: no-repeat; + background-size: 280px; + color: transparent; + display: block; + font-size: 0; + height: 20px; + line-height: 0; + width: 20px; +} + +.viewer-zoom-in::before { + background-position: 0 0; + content: 'Zoom In'; +} + +.viewer-zoom-out::before { + background-position: -20px 0; + content: 'Zoom Out'; +} + +.viewer-one-to-one::before { + background-position: -40px 0; + content: 'One to One'; +} + +.viewer-reset::before { + background-position: -60px 0; + content: 'Reset'; +} + +.viewer-prev::before { + background-position: -80px 0; + content: 'Previous'; +} + +.viewer-play::before { + background-position: -100px 0; + content: 'Play'; +} + +.viewer-next::before { + background-position: -120px 0; + content: 'Next'; +} + +.viewer-rotate-left::before { + background-position: -140px 0; + content: 'Rotate Left'; +} + +.viewer-rotate-right::before { + background-position: -160px 0; + content: 'Rotate Right'; +} + +.viewer-flip-horizontal::before { + background-position: -180px 0; + content: 'Flip Horizontal'; +} + +.viewer-flip-vertical::before { + background-position: -200px 0; + content: 'Flip Vertical'; +} + +.viewer-fullscreen::before { + background-position: -220px 0; + content: 'Enter Full Screen'; +} + +.viewer-fullscreen-exit::before { + background-position: -240px 0; + content: 'Exit Full Screen'; +} + +.viewer-close::before { + background-position: -260px 0; + content: 'Close'; +} + +.viewer-container { + bottom: 0; + direction: ltr; + font-size: 0; + left: 0; + line-height: 0; + overflow: hidden; + position: absolute; + right: 0; + -webkit-tap-highlight-color: transparent; + top: 0; + -ms-touch-action: none; + touch-action: none; + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.viewer-container::-moz-selection, +.viewer-container *::-moz-selection { + background-color: transparent; +} + +.viewer-container::selection, +.viewer-container *::selection { + background-color: transparent; +} + +.viewer-container img { + display: block; + height: auto; + max-height: none !important; + max-width: none !important; + min-height: 0 !important; + min-width: 0 !important; + width: 100%; +} + +.viewer-canvas { + bottom: 0; + left: 0; + overflow: hidden; + position: absolute; + right: 0; + top: 0; +} + +.viewer-canvas > img { + height: auto; + margin: 15px auto; + max-width: 90% !important; + width: auto; +} + +.viewer-footer { + bottom: 0; + left: 0; + overflow: hidden; + position: absolute; + right: 0; + text-align: center; +} + +.viewer-navbar { + background-color: rgba(0, 0, 0, 0.5); + overflow: hidden; +} + +.viewer-list { + -webkit-box-sizing: content-box; + box-sizing: content-box; + height: 50px; + margin: 0; + overflow: hidden; + padding: 1px 0; +} + +.viewer-list > li { + color: transparent; + cursor: pointer; + float: left; + font-size: 0; + height: 50px; + line-height: 0; + opacity: 0.5; + overflow: hidden; + -webkit-transition: opacity 0.15s; + transition: opacity 0.15s; + width: 30px; +} + +.viewer-list > li:hover { + opacity: 0.75; +} + +.viewer-list > li + li { + margin-left: 1px; +} + +.viewer-list > .viewer-loading { + position: relative; +} + +.viewer-list > .viewer-loading::after { + border-width: 2px; + height: 20px; + margin-left: -10px; + margin-top: -10px; + width: 20px; +} + +.viewer-list > .viewer-active, +.viewer-list > .viewer-active:hover { + opacity: 1; +} + +.viewer-player { + background-color: #000; + bottom: 0; + cursor: none; + display: none; + left: 0; + position: absolute; + right: 0; + top: 0; +} + +.viewer-player > img { + left: 0; + position: absolute; + top: 0; +} + +.viewer-toolbar > ul { + display: inline-block; + margin: 0 auto 5px; + overflow: hidden; + padding: 3px 0; +} + +.viewer-toolbar > ul > li { + background-color: rgba(0, 0, 0, 0.5); + border-radius: 50%; + cursor: pointer; + float: left; + height: 24px; + overflow: hidden; + -webkit-transition: background-color 0.15s; + transition: background-color 0.15s; + width: 24px; +} + +.viewer-toolbar > ul > li:hover { + background-color: rgba(0, 0, 0, 0.8); +} + +.viewer-toolbar > ul > li::before { + margin: 2px; +} + +.viewer-toolbar > ul > li + li { + margin-left: 1px; +} + +.viewer-toolbar > ul > .viewer-small { + height: 18px; + margin-bottom: 3px; + margin-top: 3px; + width: 18px; +} + +.viewer-toolbar > ul > .viewer-small::before { + margin: -1px; +} + +.viewer-toolbar > ul > .viewer-large { + height: 30px; + margin-bottom: -3px; + margin-top: -3px; + width: 30px; +} + +.viewer-toolbar > ul > .viewer-large::before { + margin: 5px; +} + +.viewer-tooltip { + background-color: rgba(0, 0, 0, 0.8); + border-radius: 10px; + color: #fff; + display: none; + font-size: 12px; + height: 20px; + left: 50%; + line-height: 20px; + margin-left: -25px; + margin-top: -10px; + position: absolute; + text-align: center; + top: 50%; + width: 50px; +} + +.viewer-title { + color: #ccc; + display: inline-block; + font-size: 12px; + line-height: 1; + margin: 0 5% 5px; + max-width: 90%; + opacity: 0.8; + overflow: hidden; + text-overflow: ellipsis; + -webkit-transition: opacity 0.15s; + transition: opacity 0.15s; + white-space: nowrap; +} + +.viewer-title:hover { + opacity: 1; +} + +.viewer-button { + background-color: rgba(0, 0, 0, 0.5); + border-radius: 50%; + cursor: pointer; + height: 80px; + overflow: hidden; + position: absolute; + right: -40px; + top: -40px; + -webkit-transition: background-color 0.15s; + transition: background-color 0.15s; + width: 80px; +} + +.viewer-button:focus, +.viewer-button:hover { + background-color: rgba(0, 0, 0, 0.8); +} + +.viewer-button::before { + bottom: 15px; + left: 15px; + position: absolute; +} + +.viewer-fixed { + position: fixed; +} + +.viewer-open { + overflow: hidden; +} + +.viewer-show { + display: block; +} + +.viewer-hide { + display: none; +} + +.viewer-backdrop { + background-color: rgba(0, 0, 0, 0.5); +} + +.viewer-invisible { + visibility: hidden; +} + +.viewer-move { + cursor: move; + cursor: -webkit-grab; + cursor: grab; +} + +.viewer-fade { + opacity: 0; +} + +.viewer-in { + opacity: 1; +} + +.viewer-transition { + -webkit-transition: all 0.3s; + transition: all 0.3s; +} + +@-webkit-keyframes viewer-spinner { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + + 100% { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes viewer-spinner { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + + 100% { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +.viewer-loading::after { + -webkit-animation: viewer-spinner 1s linear infinite; + animation: viewer-spinner 1s linear infinite; + border: 4px solid rgba(255, 255, 255, 0.1); + border-left-color: rgba(255, 255, 255, 0.5); + border-radius: 50%; + content: ''; + display: inline-block; + height: 40px; + left: 50%; + margin-left: -20px; + margin-top: -20px; + position: absolute; + top: 50%; + width: 40px; + z-index: 1; +} + +@media (max-width: 767px) { + .viewer-hide-xs-down { + display: none; + } +} + +@media (max-width: 991px) { + .viewer-hide-sm-down { + display: none; + } +} + +@media (max-width: 1199px) { + .viewer-hide-md-down { + display: none; + } +} diff --git a/static/viewerjs/viewer.js b/static/viewerjs/viewer.js new file mode 100644 index 0000000..229b9c2 --- /dev/null +++ b/static/viewerjs/viewer.js @@ -0,0 +1,3117 @@ +/*! + * Viewer.js v1.5.0 + * https://fengyuanchen.github.io/viewerjs + * + * Copyright 2015-present Chen Fengyuan + * Released under the MIT license + * + * Date: 2019-11-23T05:10:26.193Z + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.Viewer = factory()); +}(this, (function () { 'use strict'; + + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; + } + + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; + } + + var DEFAULTS = { + /** + * Enable a modal backdrop, specify `static` for a backdrop + * which doesn't close the modal on click. + * @type {boolean} + */ + backdrop: true, + + /** + * Show the button on the top-right of the viewer. + * @type {boolean} + */ + button: true, + + /** + * Show the navbar. + * @type {boolean | number} + */ + navbar: true, + + /** + * Specify the visibility and the content of the title. + * @type {boolean | number | Function | Array} + */ + title: true, + + /** + * Show the toolbar. + * @type {boolean | number | Object} + */ + toolbar: true, + + /** + * Custom class name(s) to add to the viewer's root element. + * @type {string} + */ + className: '', + + /** + * Define where to put the viewer in modal mode. + * @type {string | Element} + */ + container: 'body', + + /** + * Filter the images for viewing. Return true if the image is viewable. + * @type {Function} + */ + filter: null, + + /** + * Enable to request fullscreen when play. + * @type {boolean} + */ + fullscreen: true, + + /** + * Define the initial index of image for viewing. + * @type {number} + */ + initialViewIndex: 0, + + /** + * Enable inline mode. + * @type {boolean} + */ + inline: false, + + /** + * The amount of time to delay between automatically cycling an image when playing. + * @type {number} + */ + interval: 5000, + + /** + * Enable keyboard support. + * @type {boolean} + */ + keyboard: true, + + /** + * Indicate if show a loading spinner when load image or not. + * @type {boolean} + */ + loading: true, + + /** + * Indicate if enable loop viewing or not. + * @type {boolean} + */ + loop: true, + + /** + * Min width of the viewer in inline mode. + * @type {number} + */ + minWidth: 200, + + /** + * Min height of the viewer in inline mode. + * @type {number} + */ + minHeight: 100, + + /** + * Enable to move the image. + * @type {boolean} + */ + movable: true, + + /** + * Enable to rotate the image. + * @type {boolean} + */ + rotatable: true, + + /** + * Enable to scale the image. + * @type {boolean} + */ + scalable: true, + + /** + * Enable to zoom the image. + * @type {boolean} + */ + zoomable: true, + + /** + * Enable to zoom the current image by dragging on the touch screen. + * @type {boolean} + */ + zoomOnTouch: true, + + /** + * Enable to zoom the image by wheeling mouse. + * @type {boolean} + */ + zoomOnWheel: true, + + /** + * Enable to slide to the next or previous image by swiping on the touch screen. + * @type {boolean} + */ + slideOnTouch: true, + + /** + * Indicate if toggle the image size between its natural size + * and initial size when double click on the image or not. + * @type {boolean} + */ + toggleOnDblclick: true, + + /** + * Show the tooltip with image ratio (percentage) when zoom in or zoom out. + * @type {boolean} + */ + tooltip: true, + + /** + * Enable CSS3 Transition for some special elements. + * @type {boolean} + */ + transition: true, + + /** + * Define the CSS `z-index` value of viewer in modal mode. + * @type {number} + */ + zIndex: 2015, + + /** + * Define the CSS `z-index` value of viewer in inline mode. + * @type {number} + */ + zIndexInline: 0, + + /** + * Define the ratio when zoom the image by wheeling mouse. + * @type {number} + */ + zoomRatio: 0.1, + + /** + * Define the min ratio of the image when zoom out. + * @type {number} + */ + minZoomRatio: 0.01, + + /** + * Define the max ratio of the image when zoom in. + * @type {number} + */ + maxZoomRatio: 100, + + /** + * Define where to get the original image URL for viewing. + * @type {string | Function} + */ + url: 'src', + + /** + * Event shortcuts. + * @type {Function} + */ + ready: null, + show: null, + shown: null, + hide: null, + hidden: null, + view: null, + viewed: null, + zoom: null, + zoomed: null + }; + + var TEMPLATE = '
' + '
' + '' + '
' + '
' + '
' + '
'; + + var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined'; + var WINDOW = IS_BROWSER ? window : {}; + var IS_TOUCH_DEVICE = IS_BROWSER ? 'ontouchstart' in WINDOW.document.documentElement : false; + var HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false; + var NAMESPACE = 'viewer'; // Actions + + var ACTION_MOVE = 'move'; + var ACTION_SWITCH = 'switch'; + var ACTION_ZOOM = 'zoom'; // Classes + + var CLASS_ACTIVE = "".concat(NAMESPACE, "-active"); + var CLASS_CLOSE = "".concat(NAMESPACE, "-close"); + var CLASS_FADE = "".concat(NAMESPACE, "-fade"); + var CLASS_FIXED = "".concat(NAMESPACE, "-fixed"); + var CLASS_FULLSCREEN = "".concat(NAMESPACE, "-fullscreen"); + var CLASS_FULLSCREEN_EXIT = "".concat(NAMESPACE, "-fullscreen-exit"); + var CLASS_HIDE = "".concat(NAMESPACE, "-hide"); + var CLASS_HIDE_MD_DOWN = "".concat(NAMESPACE, "-hide-md-down"); + var CLASS_HIDE_SM_DOWN = "".concat(NAMESPACE, "-hide-sm-down"); + var CLASS_HIDE_XS_DOWN = "".concat(NAMESPACE, "-hide-xs-down"); + var CLASS_IN = "".concat(NAMESPACE, "-in"); + var CLASS_INVISIBLE = "".concat(NAMESPACE, "-invisible"); + var CLASS_LOADING = "".concat(NAMESPACE, "-loading"); + var CLASS_MOVE = "".concat(NAMESPACE, "-move"); + var CLASS_OPEN = "".concat(NAMESPACE, "-open"); + var CLASS_SHOW = "".concat(NAMESPACE, "-show"); + var CLASS_TRANSITION = "".concat(NAMESPACE, "-transition"); // Events + + var EVENT_CLICK = 'click'; + var EVENT_DBLCLICK = 'dblclick'; + var EVENT_DRAG_START = 'dragstart'; + var EVENT_HIDDEN = 'hidden'; + var EVENT_HIDE = 'hide'; + var EVENT_KEY_DOWN = 'keydown'; + var EVENT_LOAD = 'load'; + var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown'; + var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove'; + var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup'; + var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START; + var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE; + var EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END; + var EVENT_READY = 'ready'; + var EVENT_RESIZE = 'resize'; + var EVENT_SHOW = 'show'; + var EVENT_SHOWN = 'shown'; + var EVENT_TRANSITION_END = 'transitionend'; + var EVENT_VIEW = 'view'; + var EVENT_VIEWED = 'viewed'; + var EVENT_WHEEL = 'wheel'; + var EVENT_ZOOM = 'zoom'; + var EVENT_ZOOMED = 'zoomed'; // Data keys + + var DATA_ACTION = "".concat(NAMESPACE, "Action"); // RegExps + + var REGEXP_SPACES = /\s\s*/; // Misc + + var BUTTONS = ['zoom-in', 'zoom-out', 'one-to-one', 'reset', 'prev', 'play', 'next', 'rotate-left', 'rotate-right', 'flip-horizontal', 'flip-vertical']; + + /** + * Check if the given value is a string. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a string, else `false`. + */ + + function isString(value) { + return typeof value === 'string'; + } + /** + * Check if the given value is not a number. + */ + + var isNaN = Number.isNaN || WINDOW.isNaN; + /** + * Check if the given value is a number. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a number, else `false`. + */ + + function isNumber(value) { + return typeof value === 'number' && !isNaN(value); + } + /** + * Check if the given value is undefined. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is undefined, else `false`. + */ + + function isUndefined(value) { + return typeof value === 'undefined'; + } + /** + * Check if the given value is an object. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is an object, else `false`. + */ + + function isObject(value) { + return _typeof(value) === 'object' && value !== null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Check if the given value is a plain object. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a plain object, else `false`. + */ + + function isPlainObject(value) { + if (!isObject(value)) { + return false; + } + + try { + var _constructor = value.constructor; + var prototype = _constructor.prototype; + return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf'); + } catch (error) { + return false; + } + } + /** + * Check if the given value is a function. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a function, else `false`. + */ + + function isFunction(value) { + return typeof value === 'function'; + } + /** + * Iterate the given data. + * @param {*} data - The data to iterate. + * @param {Function} callback - The process function for each element. + * @returns {*} The original data. + */ + + function forEach(data, callback) { + if (data && isFunction(callback)) { + if (Array.isArray(data) || isNumber(data.length) + /* array-like */ + ) { + var length = data.length; + var i; + + for (i = 0; i < length; i += 1) { + if (callback.call(data, data[i], i, data) === false) { + break; + } + } + } else if (isObject(data)) { + Object.keys(data).forEach(function (key) { + callback.call(data, data[key], key, data); + }); + } + } + + return data; + } + /** + * Extend the given object. + * @param {*} obj - The object to be extended. + * @param {*} args - The rest objects which will be merged to the first object. + * @returns {Object} The extended object. + */ + + var assign = Object.assign || function assign(obj) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + if (isObject(obj) && args.length > 0) { + args.forEach(function (arg) { + if (isObject(arg)) { + Object.keys(arg).forEach(function (key) { + obj[key] = arg[key]; + }); + } + }); + } + + return obj; + }; + var REGEXP_SUFFIX = /^(?:width|height|left|top|marginLeft|marginTop)$/; + /** + * Apply styles to the given element. + * @param {Element} element - The target element. + * @param {Object} styles - The styles for applying. + */ + + function setStyle(element, styles) { + var style = element.style; + forEach(styles, function (value, property) { + if (REGEXP_SUFFIX.test(property) && isNumber(value)) { + value += 'px'; + } + + style[property] = value; + }); + } + /** + * Escape a string for using in HTML. + * @param {String} value - The string to escape. + * @returns {String} Returns the escaped string. + */ + + function escapeHTMLEntities(value) { + return isString(value) ? value.replace(/&(?!amp;|quot;|#39;|lt;|gt;)/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>') : value; + } + /** + * Check if the given element has a special class. + * @param {Element} element - The element to check. + * @param {string} value - The class to search. + * @returns {boolean} Returns `true` if the special class was found. + */ + + function hasClass(element, value) { + if (!element || !value) { + return false; + } + + return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1; + } + /** + * Add classes to the given element. + * @param {Element} element - The target element. + * @param {string} value - The classes to be added. + */ + + function addClass(element, value) { + if (!element || !value) { + return; + } + + if (isNumber(element.length)) { + forEach(element, function (elem) { + addClass(elem, value); + }); + return; + } + + if (element.classList) { + element.classList.add(value); + return; + } + + var className = element.className.trim(); + + if (!className) { + element.className = value; + } else if (className.indexOf(value) < 0) { + element.className = "".concat(className, " ").concat(value); + } + } + /** + * Remove classes from the given element. + * @param {Element} element - The target element. + * @param {string} value - The classes to be removed. + */ + + function removeClass(element, value) { + if (!element || !value) { + return; + } + + if (isNumber(element.length)) { + forEach(element, function (elem) { + removeClass(elem, value); + }); + return; + } + + if (element.classList) { + element.classList.remove(value); + return; + } + + if (element.className.indexOf(value) >= 0) { + element.className = element.className.replace(value, ''); + } + } + /** + * Add or remove classes from the given element. + * @param {Element} element - The target element. + * @param {string} value - The classes to be toggled. + * @param {boolean} added - Add only. + */ + + function toggleClass(element, value, added) { + if (!value) { + return; + } + + if (isNumber(element.length)) { + forEach(element, function (elem) { + toggleClass(elem, value, added); + }); + return; + } // IE10-11 doesn't support the second parameter of `classList.toggle` + + + if (added) { + addClass(element, value); + } else { + removeClass(element, value); + } + } + var REGEXP_HYPHENATE = /([a-z\d])([A-Z])/g; + /** + * Transform the given string from camelCase to kebab-case + * @param {string} value - The value to transform. + * @returns {string} The transformed value. + */ + + function hyphenate(value) { + return value.replace(REGEXP_HYPHENATE, '$1-$2').toLowerCase(); + } + /** + * Get data from the given element. + * @param {Element} element - The target element. + * @param {string} name - The data key to get. + * @returns {string} The data value. + */ + + function getData(element, name) { + if (isObject(element[name])) { + return element[name]; + } + + if (element.dataset) { + return element.dataset[name]; + } + + return element.getAttribute("data-".concat(hyphenate(name))); + } + /** + * Set data to the given element. + * @param {Element} element - The target element. + * @param {string} name - The data key to set. + * @param {string} data - The data value. + */ + + function setData(element, name, data) { + if (isObject(data)) { + element[name] = data; + } else if (element.dataset) { + element.dataset[name] = data; + } else { + element.setAttribute("data-".concat(hyphenate(name)), data); + } + } + + var onceSupported = function () { + var supported = false; + + if (IS_BROWSER) { + var once = false; + + var listener = function listener() {}; + + var options = Object.defineProperty({}, 'once', { + get: function get() { + supported = true; + return once; + }, + + /** + * This setter can fix a `TypeError` in strict mode + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only} + * @param {boolean} value - The value to set + */ + set: function set(value) { + once = value; + } + }); + WINDOW.addEventListener('test', listener, options); + WINDOW.removeEventListener('test', listener, options); + } + + return supported; + }(); + /** + * Remove event listener from the target element. + * @param {Element} element - The event target. + * @param {string} type - The event type(s). + * @param {Function} listener - The event listener. + * @param {Object} options - The event options. + */ + + + function removeListener(element, type, listener) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var handler = listener; + type.trim().split(REGEXP_SPACES).forEach(function (event) { + if (!onceSupported) { + var listeners = element.listeners; + + if (listeners && listeners[event] && listeners[event][listener]) { + handler = listeners[event][listener]; + delete listeners[event][listener]; + + if (Object.keys(listeners[event]).length === 0) { + delete listeners[event]; + } + + if (Object.keys(listeners).length === 0) { + delete element.listeners; + } + } + } + + element.removeEventListener(event, handler, options); + }); + } + /** + * Add event listener to the target element. + * @param {Element} element - The event target. + * @param {string} type - The event type(s). + * @param {Function} listener - The event listener. + * @param {Object} options - The event options. + */ + + function addListener(element, type, listener) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var _handler = listener; + type.trim().split(REGEXP_SPACES).forEach(function (event) { + if (options.once && !onceSupported) { + var _element$listeners = element.listeners, + listeners = _element$listeners === void 0 ? {} : _element$listeners; + + _handler = function handler() { + delete listeners[event][listener]; + element.removeEventListener(event, _handler, options); + + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + listener.apply(element, args); + }; + + if (!listeners[event]) { + listeners[event] = {}; + } + + if (listeners[event][listener]) { + element.removeEventListener(event, listeners[event][listener], options); + } + + listeners[event][listener] = _handler; + element.listeners = listeners; + } + + element.addEventListener(event, _handler, options); + }); + } + /** + * Dispatch event on the target element. + * @param {Element} element - The event target. + * @param {string} type - The event type(s). + * @param {Object} data - The additional event data. + * @returns {boolean} Indicate if the event is default prevented or not. + */ + + function dispatchEvent(element, type, data) { + var event; // Event and CustomEvent on IE9-11 are global objects, not constructors + + if (isFunction(Event) && isFunction(CustomEvent)) { + event = new CustomEvent(type, { + detail: data, + bubbles: true, + cancelable: true + }); + } else { + event = document.createEvent('CustomEvent'); + event.initCustomEvent(type, true, true, data); + } + + return element.dispatchEvent(event); + } + /** + * Get the offset base on the document. + * @param {Element} element - The target element. + * @returns {Object} The offset data. + */ + + function getOffset(element) { + var box = element.getBoundingClientRect(); + return { + left: box.left + (window.pageXOffset - document.documentElement.clientLeft), + top: box.top + (window.pageYOffset - document.documentElement.clientTop) + }; + } + /** + * Get transforms base on the given object. + * @param {Object} obj - The target object. + * @returns {string} A string contains transform values. + */ + + function getTransforms(_ref) { + var rotate = _ref.rotate, + scaleX = _ref.scaleX, + scaleY = _ref.scaleY, + translateX = _ref.translateX, + translateY = _ref.translateY; + var values = []; + + if (isNumber(translateX) && translateX !== 0) { + values.push("translateX(".concat(translateX, "px)")); + } + + if (isNumber(translateY) && translateY !== 0) { + values.push("translateY(".concat(translateY, "px)")); + } // Rotate should come first before scale to match orientation transform + + + if (isNumber(rotate) && rotate !== 0) { + values.push("rotate(".concat(rotate, "deg)")); + } + + if (isNumber(scaleX) && scaleX !== 1) { + values.push("scaleX(".concat(scaleX, ")")); + } + + if (isNumber(scaleY) && scaleY !== 1) { + values.push("scaleY(".concat(scaleY, ")")); + } + + var transform = values.length ? values.join(' ') : 'none'; + return { + WebkitTransform: transform, + msTransform: transform, + transform: transform + }; + } + /** + * Get an image name from an image url. + * @param {string} url - The target url. + * @example + * // picture.jpg + * getImageNameFromURL('https://domain.com/path/to/picture.jpg?size=1280×960') + * @returns {string} A string contains the image name. + */ + + function getImageNameFromURL(url) { + return isString(url) ? decodeURIComponent(url.replace(/^.*\//, '').replace(/[?&#].*$/, '')) : ''; + } + var IS_SAFARI = WINDOW.navigator && /(Macintosh|iPhone|iPod|iPad).*AppleWebKit/i.test(WINDOW.navigator.userAgent); + /** + * Get an image's natural sizes. + * @param {string} image - The target image. + * @param {Function} callback - The callback function. + * @returns {HTMLImageElement} The new image. + */ + + function getImageNaturalSizes(image, callback) { + var newImage = document.createElement('img'); // Modern browsers (except Safari) + + if (image.naturalWidth && !IS_SAFARI) { + callback(image.naturalWidth, image.naturalHeight); + return newImage; + } + + var body = document.body || document.documentElement; + + newImage.onload = function () { + callback(newImage.width, newImage.height); + + if (!IS_SAFARI) { + body.removeChild(newImage); + } + }; + + newImage.src = image.src; // iOS Safari will convert the image automatically + // with its orientation once append it into DOM + + if (!IS_SAFARI) { + newImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;'; + body.appendChild(newImage); + } + + return newImage; + } + /** + * Get the related class name of a responsive type number. + * @param {string} type - The responsive type. + * @returns {string} The related class name. + */ + + function getResponsiveClass(type) { + switch (type) { + case 2: + return CLASS_HIDE_XS_DOWN; + + case 3: + return CLASS_HIDE_SM_DOWN; + + case 4: + return CLASS_HIDE_MD_DOWN; + + default: + return ''; + } + } + /** + * Get the max ratio of a group of pointers. + * @param {string} pointers - The target pointers. + * @returns {number} The result ratio. + */ + + function getMaxZoomRatio(pointers) { + var pointers2 = _objectSpread2({}, pointers); + + var ratios = []; + forEach(pointers, function (pointer, pointerId) { + delete pointers2[pointerId]; + forEach(pointers2, function (pointer2) { + var x1 = Math.abs(pointer.startX - pointer2.startX); + var y1 = Math.abs(pointer.startY - pointer2.startY); + var x2 = Math.abs(pointer.endX - pointer2.endX); + var y2 = Math.abs(pointer.endY - pointer2.endY); + var z1 = Math.sqrt(x1 * x1 + y1 * y1); + var z2 = Math.sqrt(x2 * x2 + y2 * y2); + var ratio = (z2 - z1) / z1; + ratios.push(ratio); + }); + }); + ratios.sort(function (a, b) { + return Math.abs(a) < Math.abs(b); + }); + return ratios[0]; + } + /** + * Get a pointer from an event object. + * @param {Object} event - The target event object. + * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not. + * @returns {Object} The result pointer contains start and/or end point coordinates. + */ + + function getPointer(_ref2, endOnly) { + var pageX = _ref2.pageX, + pageY = _ref2.pageY; + var end = { + endX: pageX, + endY: pageY + }; + return endOnly ? end : _objectSpread2({ + timeStamp: Date.now(), + startX: pageX, + startY: pageY + }, end); + } + /** + * Get the center point coordinate of a group of pointers. + * @param {Object} pointers - The target pointers. + * @returns {Object} The center point coordinate. + */ + + function getPointersCenter(pointers) { + var pageX = 0; + var pageY = 0; + var count = 0; + forEach(pointers, function (_ref3) { + var startX = _ref3.startX, + startY = _ref3.startY; + pageX += startX; + pageY += startY; + count += 1; + }); + pageX /= count; + pageY /= count; + return { + pageX: pageX, + pageY: pageY + }; + } + + var render = { + render: function render() { + this.initContainer(); + this.initViewer(); + this.initList(); + this.renderViewer(); + }, + initContainer: function initContainer() { + this.containerData = { + width: window.innerWidth, + height: window.innerHeight + }; + }, + initViewer: function initViewer() { + var options = this.options, + parent = this.parent; + var viewerData; + + if (options.inline) { + viewerData = { + width: Math.max(parent.offsetWidth, options.minWidth), + height: Math.max(parent.offsetHeight, options.minHeight) + }; + this.parentData = viewerData; + } + + if (this.fulled || !viewerData) { + viewerData = this.containerData; + } + + this.viewerData = assign({}, viewerData); + }, + renderViewer: function renderViewer() { + if (this.options.inline && !this.fulled) { + setStyle(this.viewer, this.viewerData); + } + }, + initList: function initList() { + var _this = this; + + var element = this.element, + options = this.options, + list = this.list; + var items = []; // initList may be called in this.update, so should keep idempotent + + list.innerHTML = ''; + forEach(this.images, function (image, index) { + var src = image.src; + var alt = image.alt || getImageNameFromURL(src); + var url = options.url; + + if (isString(url)) { + url = image.getAttribute(url); + } else if (isFunction(url)) { + url = url.call(_this, image); + } + + if (src || url) { + var item = document.createElement('li'); + var img = document.createElement('img'); + img.src = src || url; + img.alt = alt; + img.setAttribute('data-index', index); + img.setAttribute('data-original-url', url || src); + img.setAttribute('data-viewer-action', 'view'); + img.setAttribute('role', 'button'); + item.appendChild(img); + list.appendChild(item); + items.push(item); + } + }); + this.items = items; + forEach(items, function (item) { + var image = item.firstElementChild; + setData(image, 'filled', true); + + if (options.loading) { + addClass(item, CLASS_LOADING); + } + + addListener(image, EVENT_LOAD, function (event) { + if (options.loading) { + removeClass(item, CLASS_LOADING); + } + + _this.loadImage(event); + }, { + once: true + }); + }); + + if (options.transition) { + addListener(element, EVENT_VIEWED, function () { + addClass(list, CLASS_TRANSITION); + }, { + once: true + }); + } + }, + renderList: function renderList(index) { + var i = index || this.index; + var width = this.items[i].offsetWidth || 30; + var outerWidth = width + 1; // 1 pixel of `margin-left` width + // Place the active item in the center of the screen + + setStyle(this.list, assign({ + width: outerWidth * this.length + }, getTransforms({ + translateX: (this.viewerData.width - width) / 2 - outerWidth * i + }))); + }, + resetList: function resetList() { + var list = this.list; + list.innerHTML = ''; + removeClass(list, CLASS_TRANSITION); + setStyle(list, getTransforms({ + translateX: 0 + })); + }, + initImage: function initImage(done) { + var _this2 = this; + + var options = this.options, + image = this.image, + viewerData = this.viewerData; + var footerHeight = this.footer.offsetHeight; + var viewerWidth = viewerData.width; + var viewerHeight = Math.max(viewerData.height - footerHeight, footerHeight); + var oldImageData = this.imageData || {}; + var sizingImage; + this.imageInitializing = { + abort: function abort() { + sizingImage.onload = null; + } + }; + sizingImage = getImageNaturalSizes(image, function (naturalWidth, naturalHeight) { + var aspectRatio = naturalWidth / naturalHeight; + var width = viewerWidth; + var height = viewerHeight; + _this2.imageInitializing = false; + + if (viewerHeight * aspectRatio > viewerWidth) { + height = viewerWidth / aspectRatio; + } else { + width = viewerHeight * aspectRatio; + } + + width = Math.min(width * 0.9, naturalWidth); + height = Math.min(height * 0.9, naturalHeight); + var imageData = { + naturalWidth: naturalWidth, + naturalHeight: naturalHeight, + aspectRatio: aspectRatio, + ratio: width / naturalWidth, + width: width, + height: height, + left: (viewerWidth - width) / 2, + top: (viewerHeight - height) / 2 + }; + var initialImageData = assign({}, imageData); + + if (options.rotatable) { + imageData.rotate = oldImageData.rotate || 0; + initialImageData.rotate = 0; + } + + if (options.scalable) { + imageData.scaleX = oldImageData.scaleX || 1; + imageData.scaleY = oldImageData.scaleY || 1; + initialImageData.scaleX = 1; + initialImageData.scaleY = 1; + } + + _this2.imageData = imageData; + _this2.initialImageData = initialImageData; + + if (done) { + done(); + } + }); + }, + renderImage: function renderImage(done) { + var _this3 = this; + + var image = this.image, + imageData = this.imageData; + setStyle(image, assign({ + width: imageData.width, + height: imageData.height, + // XXX: Not to use translateX/Y to avoid image shaking when zooming + marginLeft: imageData.left, + marginTop: imageData.top + }, getTransforms(imageData))); + + if (done) { + if ((this.viewing || this.zooming) && this.options.transition) { + var onTransitionEnd = function onTransitionEnd() { + _this3.imageRendering = false; + done(); + }; + + this.imageRendering = { + abort: function abort() { + removeListener(image, EVENT_TRANSITION_END, onTransitionEnd); + } + }; + addListener(image, EVENT_TRANSITION_END, onTransitionEnd, { + once: true + }); + } else { + done(); + } + } + }, + resetImage: function resetImage() { + // this.image only defined after viewed + if (this.viewing || this.viewed) { + var image = this.image; + + if (this.viewing) { + this.viewing.abort(); + } + + image.parentNode.removeChild(image); + this.image = null; + } + } + }; + + var events = { + bind: function bind() { + var options = this.options, + viewer = this.viewer, + canvas = this.canvas; + var document = this.element.ownerDocument; + addListener(viewer, EVENT_CLICK, this.onClick = this.click.bind(this)); + addListener(viewer, EVENT_DRAG_START, this.onDragStart = this.dragstart.bind(this)); + addListener(canvas, EVENT_POINTER_DOWN, this.onPointerDown = this.pointerdown.bind(this)); + addListener(document, EVENT_POINTER_MOVE, this.onPointerMove = this.pointermove.bind(this)); + addListener(document, EVENT_POINTER_UP, this.onPointerUp = this.pointerup.bind(this)); + addListener(document, EVENT_KEY_DOWN, this.onKeyDown = this.keydown.bind(this)); + addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this)); + + if (options.zoomable && options.zoomOnWheel) { + addListener(viewer, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), { + passive: false, + capture: true + }); + } + + if (options.toggleOnDblclick) { + addListener(canvas, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this)); + } + }, + unbind: function unbind() { + var options = this.options, + viewer = this.viewer, + canvas = this.canvas; + var document = this.element.ownerDocument; + removeListener(viewer, EVENT_CLICK, this.onClick); + removeListener(viewer, EVENT_DRAG_START, this.onDragStart); + removeListener(canvas, EVENT_POINTER_DOWN, this.onPointerDown); + removeListener(document, EVENT_POINTER_MOVE, this.onPointerMove); + removeListener(document, EVENT_POINTER_UP, this.onPointerUp); + removeListener(document, EVENT_KEY_DOWN, this.onKeyDown); + removeListener(window, EVENT_RESIZE, this.onResize); + + if (options.zoomable && options.zoomOnWheel) { + removeListener(viewer, EVENT_WHEEL, this.onWheel, { + passive: false, + capture: true + }); + } + + if (options.toggleOnDblclick) { + removeListener(canvas, EVENT_DBLCLICK, this.onDblclick); + } + } + }; + + var handlers = { + click: function click(event) { + var target = event.target; + var options = this.options, + imageData = this.imageData; + var action = getData(target, DATA_ACTION); // Cancel the emulated click when the native click event was triggered. + + if (IS_TOUCH_DEVICE && event.isTrusted && target === this.canvas) { + clearTimeout(this.clickCanvasTimeout); + } + + switch (action) { + case 'mix': + if (this.played) { + this.stop(); + } else if (options.inline) { + if (this.fulled) { + this.exit(); + } else { + this.full(); + } + } else { + this.hide(); + } + + break; + + case 'hide': + this.hide(); + break; + + case 'view': + this.view(getData(target, 'index')); + break; + + case 'zoom-in': + this.zoom(0.1, true); + break; + + case 'zoom-out': + this.zoom(-0.1, true); + break; + + case 'one-to-one': + this.toggle(); + break; + + case 'reset': + this.reset(); + break; + + case 'prev': + this.prev(options.loop); + break; + + case 'play': + this.play(options.fullscreen); + break; + + case 'next': + this.next(options.loop); + break; + + case 'rotate-left': + this.rotate(-90); + break; + + case 'rotate-right': + this.rotate(90); + break; + + case 'flip-horizontal': + this.scaleX(-imageData.scaleX || -1); + break; + + case 'flip-vertical': + this.scaleY(-imageData.scaleY || -1); + break; + + default: + if (this.played) { + this.stop(); + } + + } + }, + dblclick: function dblclick(event) { + event.preventDefault(); + + if (this.viewed && event.target === this.image) { + // Cancel the emulated double click when the native dblclick event was triggered. + if (IS_TOUCH_DEVICE && event.isTrusted) { + clearTimeout(this.doubleClickImageTimeout); + } + + this.toggle(); + } + }, + load: function load() { + var _this = this; + + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = false; + } + + var element = this.element, + options = this.options, + image = this.image, + index = this.index, + viewerData = this.viewerData; + removeClass(image, CLASS_INVISIBLE); + + if (options.loading) { + removeClass(this.canvas, CLASS_LOADING); + } + + image.style.cssText = 'height:0;' + "margin-left:".concat(viewerData.width / 2, "px;") + "margin-top:".concat(viewerData.height / 2, "px;") + 'max-width:none!important;' + 'position:absolute;' + 'width:0;'; + this.initImage(function () { + toggleClass(image, CLASS_MOVE, options.movable); + toggleClass(image, CLASS_TRANSITION, options.transition); + + _this.renderImage(function () { + _this.viewed = true; + _this.viewing = false; + + if (isFunction(options.viewed)) { + addListener(element, EVENT_VIEWED, options.viewed, { + once: true + }); + } + + dispatchEvent(element, EVENT_VIEWED, { + originalImage: _this.images[index], + index: index, + image: image + }); + }); + }); + }, + loadImage: function loadImage(event) { + var image = event.target; + var parent = image.parentNode; + var parentWidth = parent.offsetWidth || 30; + var parentHeight = parent.offsetHeight || 50; + var filled = !!getData(image, 'filled'); + getImageNaturalSizes(image, function (naturalWidth, naturalHeight) { + var aspectRatio = naturalWidth / naturalHeight; + var width = parentWidth; + var height = parentHeight; + + if (parentHeight * aspectRatio > parentWidth) { + if (filled) { + width = parentHeight * aspectRatio; + } else { + height = parentWidth / aspectRatio; + } + } else if (filled) { + height = parentWidth / aspectRatio; + } else { + width = parentHeight * aspectRatio; + } + + setStyle(image, assign({ + width: width, + height: height + }, getTransforms({ + translateX: (parentWidth - width) / 2, + translateY: (parentHeight - height) / 2 + }))); + }); + }, + keydown: function keydown(event) { + var options = this.options; + + if (!this.fulled || !options.keyboard) { + return; + } + + switch (event.keyCode || event.which || event.charCode) { + // Escape + case 27: + if (this.played) { + this.stop(); + } else if (options.inline) { + if (this.fulled) { + this.exit(); + } + } else { + this.hide(); + } + + break; + // Space + + case 32: + if (this.played) { + this.stop(); + } + + break; + // ArrowLeft + + case 37: + this.prev(options.loop); + break; + // ArrowUp + + case 38: + // Prevent scroll on Firefox + event.preventDefault(); // Zoom in + + this.zoom(options.zoomRatio, true); + break; + // ArrowRight + + case 39: + this.next(options.loop); + break; + // ArrowDown + + case 40: + // Prevent scroll on Firefox + event.preventDefault(); // Zoom out + + this.zoom(-options.zoomRatio, true); + break; + // Ctrl + 0 + + case 48: // Fall through + // Ctrl + 1 + // eslint-disable-next-line no-fallthrough + + case 49: + if (event.ctrlKey) { + event.preventDefault(); + this.toggle(); + } + + break; + } + }, + dragstart: function dragstart(event) { + if (event.target.tagName.toLowerCase() === 'img') { + event.preventDefault(); + } + }, + pointerdown: function pointerdown(event) { + var options = this.options, + pointers = this.pointers; + var buttons = event.buttons, + button = event.button; + + if (!this.viewed || this.showing || this.viewing || this.hiding // Handle mouse event and pointer event and ignore touch event + || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && ( // No primary button (Usually the left button) + isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 // Open context menu + || event.ctrlKey)) { + return; + } // Prevent default behaviours as page zooming in touch devices. + + + event.preventDefault(); + + if (event.changedTouches) { + forEach(event.changedTouches, function (touch) { + pointers[touch.identifier] = getPointer(touch); + }); + } else { + pointers[event.pointerId || 0] = getPointer(event); + } + + var action = options.movable ? ACTION_MOVE : false; + + if (options.zoomOnTouch && options.zoomable && Object.keys(pointers).length > 1) { + action = ACTION_ZOOM; + } else if (options.slideOnTouch && (event.pointerType === 'touch' || event.type === 'touchstart') && this.isSwitchable()) { + action = ACTION_SWITCH; + } + + if (options.transition && (action === ACTION_MOVE || action === ACTION_ZOOM)) { + removeClass(this.image, CLASS_TRANSITION); + } + + this.action = action; + }, + pointermove: function pointermove(event) { + var pointers = this.pointers, + action = this.action; + + if (!this.viewed || !action) { + return; + } + + event.preventDefault(); + + if (event.changedTouches) { + forEach(event.changedTouches, function (touch) { + assign(pointers[touch.identifier] || {}, getPointer(touch, true)); + }); + } else { + assign(pointers[event.pointerId || 0] || {}, getPointer(event, true)); + } + + this.change(event); + }, + pointerup: function pointerup(event) { + var _this2 = this; + + var options = this.options, + action = this.action, + pointers = this.pointers; + var pointer; + + if (event.changedTouches) { + forEach(event.changedTouches, function (touch) { + pointer = pointers[touch.identifier]; + delete pointers[touch.identifier]; + }); + } else { + pointer = pointers[event.pointerId || 0]; + delete pointers[event.pointerId || 0]; + } + + if (!action) { + return; + } + + event.preventDefault(); + + if (options.transition && (action === ACTION_MOVE || action === ACTION_ZOOM)) { + addClass(this.image, CLASS_TRANSITION); + } + + this.action = false; // Emulate click and double click in touch devices to support backdrop and image zooming (#210). + + if (IS_TOUCH_DEVICE && action !== ACTION_ZOOM && pointer && Date.now() - pointer.timeStamp < 500) { + clearTimeout(this.clickCanvasTimeout); + clearTimeout(this.doubleClickImageTimeout); + + if (options.toggleOnDblclick && this.viewed && event.target === this.image) { + if (this.imageClicked) { + this.imageClicked = false; // This timeout will be cleared later when a native dblclick event is triggering + + this.doubleClickImageTimeout = setTimeout(function () { + dispatchEvent(_this2.image, EVENT_DBLCLICK); + }, 50); + } else { + this.imageClicked = true; // The default timing of a double click in Windows is 500 ms + + this.doubleClickImageTimeout = setTimeout(function () { + _this2.imageClicked = false; + }, 500); + } + } else { + this.imageClicked = false; + + if (options.backdrop && options.backdrop !== 'static' && event.target === this.canvas) { + // This timeout will be cleared later when a native click event is triggering + this.clickCanvasTimeout = setTimeout(function () { + dispatchEvent(_this2.canvas, EVENT_CLICK); + }, 50); + } + } + } + }, + resize: function resize() { + var _this3 = this; + + if (!this.isShown || this.hiding) { + return; + } + + this.initContainer(); + this.initViewer(); + this.renderViewer(); + this.renderList(); + + if (this.viewed) { + this.initImage(function () { + _this3.renderImage(); + }); + } + + if (this.played) { + if (this.options.fullscreen && this.fulled && !(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement)) { + this.stop(); + return; + } + + forEach(this.player.getElementsByTagName('img'), function (image) { + addListener(image, EVENT_LOAD, _this3.loadImage.bind(_this3), { + once: true + }); + dispatchEvent(image, EVENT_LOAD); + }); + } + }, + wheel: function wheel(event) { + var _this4 = this; + + if (!this.viewed) { + return; + } + + event.preventDefault(); // Limit wheel speed to prevent zoom too fast + + if (this.wheeling) { + return; + } + + this.wheeling = true; + setTimeout(function () { + _this4.wheeling = false; + }, 50); + var ratio = Number(this.options.zoomRatio) || 0.1; + var delta = 1; + + if (event.deltaY) { + delta = event.deltaY > 0 ? 1 : -1; + } else if (event.wheelDelta) { + delta = -event.wheelDelta / 120; + } else if (event.detail) { + delta = event.detail > 0 ? 1 : -1; + } + + this.zoom(-delta * ratio, true, event); + } + }; + + var methods = { + /** Show the viewer (only available in modal mode) + * @param {boolean} [immediate=false] - Indicates if show the viewer immediately or not. + * @returns {Viewer} this + */ + show: function show() { + var immediate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var element = this.element, + options = this.options; + + if (options.inline || this.showing || this.isShown || this.showing) { + return this; + } + + if (!this.ready) { + this.build(); + + if (this.ready) { + this.show(immediate); + } + + return this; + } + + if (isFunction(options.show)) { + addListener(element, EVENT_SHOW, options.show, { + once: true + }); + } + + if (dispatchEvent(element, EVENT_SHOW) === false || !this.ready) { + return this; + } + + if (this.hiding) { + this.transitioning.abort(); + } + + this.showing = true; + this.open(); + var viewer = this.viewer; + removeClass(viewer, CLASS_HIDE); + + if (options.transition && !immediate) { + var shown = this.shown.bind(this); + this.transitioning = { + abort: function abort() { + removeListener(viewer, EVENT_TRANSITION_END, shown); + removeClass(viewer, CLASS_IN); + } + }; + addClass(viewer, CLASS_TRANSITION); // Force reflow to enable CSS3 transition + + viewer.initialOffsetWidth = viewer.offsetWidth; + addListener(viewer, EVENT_TRANSITION_END, shown, { + once: true + }); + addClass(viewer, CLASS_IN); + } else { + addClass(viewer, CLASS_IN); + this.shown(); + } + + return this; + }, + + /** + * Hide the viewer (only available in modal mode) + * @param {boolean} [immediate=false] - Indicates if hide the viewer immediately or not. + * @returns {Viewer} this + */ + hide: function hide() { + var immediate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var element = this.element, + options = this.options; + + if (options.inline || this.hiding || !(this.isShown || this.showing)) { + return this; + } + + if (isFunction(options.hide)) { + addListener(element, EVENT_HIDE, options.hide, { + once: true + }); + } + + if (dispatchEvent(element, EVENT_HIDE) === false) { + return this; + } + + if (this.showing) { + this.transitioning.abort(); + } + + this.hiding = true; + + if (this.played) { + this.stop(); + } else if (this.viewing) { + this.viewing.abort(); + } + + var viewer = this.viewer; + + if (options.transition && !immediate) { + var hidden = this.hidden.bind(this); + + var hide = function hide() { + // XXX: It seems the `event.stopPropagation()` method does not work here + setTimeout(function () { + addListener(viewer, EVENT_TRANSITION_END, hidden, { + once: true + }); + removeClass(viewer, CLASS_IN); + }, 0); + }; + + this.transitioning = { + abort: function abort() { + if (this.viewed) { + removeListener(this.image, EVENT_TRANSITION_END, hide); + } else { + removeListener(viewer, EVENT_TRANSITION_END, hidden); + } + } + }; // Note that the `CLASS_TRANSITION` class will be removed on pointer down (#255) + + if (this.viewed && hasClass(this.image, CLASS_TRANSITION)) { + addListener(this.image, EVENT_TRANSITION_END, hide, { + once: true + }); + this.zoomTo(0, false, false, true); + } else { + hide(); + } + } else { + removeClass(viewer, CLASS_IN); + this.hidden(); + } + + return this; + }, + + /** + * View one of the images with image's index + * @param {number} index - The index of the image to view. + * @returns {Viewer} this + */ + view: function view() { + var _this = this; + + var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.options.initialViewIndex; + index = Number(index) || 0; + + if (this.hiding || this.played || index < 0 || index >= this.length || this.viewed && index === this.index) { + return this; + } + + if (!this.isShown) { + this.index = index; + return this.show(); + } + + if (this.viewing) { + this.viewing.abort(); + } + + var element = this.element, + options = this.options, + title = this.title, + canvas = this.canvas; + var item = this.items[index]; + var img = item.querySelector('img'); + var url = getData(img, 'originalUrl'); + var alt = img.getAttribute('alt'); + var image = document.createElement('img'); + image.src = url; + image.alt = alt; + + if (isFunction(options.view)) { + addListener(element, EVENT_VIEW, options.view, { + once: true + }); + } + + if (dispatchEvent(element, EVENT_VIEW, { + originalImage: this.images[index], + index: index, + image: image + }) === false || !this.isShown || this.hiding || this.played) { + return this; + } + + this.image = image; + removeClass(this.items[this.index], CLASS_ACTIVE); + addClass(item, CLASS_ACTIVE); + this.viewed = false; + this.index = index; + this.imageData = {}; + addClass(image, CLASS_INVISIBLE); + + if (options.loading) { + addClass(canvas, CLASS_LOADING); + } + + canvas.innerHTML = ''; + canvas.appendChild(image); // Center current item + + this.renderList(); // Clear title + + title.innerHTML = ''; // Generate title after viewed + + var onViewed = function onViewed() { + var imageData = _this.imageData; + var render = Array.isArray(options.title) ? options.title[1] : options.title; + title.innerHTML = escapeHTMLEntities(isFunction(render) ? render.call(_this, image, imageData) : "".concat(alt, " (").concat(imageData.naturalWidth, " \xD7 ").concat(imageData.naturalHeight, ")")); + }; + + var onLoad; + addListener(element, EVENT_VIEWED, onViewed, { + once: true + }); + this.viewing = { + abort: function abort() { + removeListener(element, EVENT_VIEWED, onViewed); + + if (image.complete) { + if (this.imageRendering) { + this.imageRendering.abort(); + } else if (this.imageInitializing) { + this.imageInitializing.abort(); + } + } else { + // Cancel download to save bandwidth. + image.src = ''; + removeListener(image, EVENT_LOAD, onLoad); + + if (this.timeout) { + clearTimeout(this.timeout); + } + } + } + }; + + if (image.complete) { + this.load(); + } else { + addListener(image, EVENT_LOAD, onLoad = this.load.bind(this), { + once: true + }); + + if (this.timeout) { + clearTimeout(this.timeout); + } // Make the image visible if it fails to load within 1s + + + this.timeout = setTimeout(function () { + removeClass(image, CLASS_INVISIBLE); + _this.timeout = false; + }, 1000); + } + + return this; + }, + + /** + * View the previous image + * @param {boolean} [loop=false] - Indicate if view the last one + * when it is the first one at present. + * @returns {Viewer} this + */ + prev: function prev() { + var loop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var index = this.index - 1; + + if (index < 0) { + index = loop ? this.length - 1 : 0; + } + + this.view(index); + return this; + }, + + /** + * View the next image + * @param {boolean} [loop=false] - Indicate if view the first one + * when it is the last one at present. + * @returns {Viewer} this + */ + next: function next() { + var loop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var maxIndex = this.length - 1; + var index = this.index + 1; + + if (index > maxIndex) { + index = loop ? 0 : maxIndex; + } + + this.view(index); + return this; + }, + + /** + * Move the image with relative offsets. + * @param {number} offsetX - The relative offset distance on the x-axis. + * @param {number} offsetY - The relative offset distance on the y-axis. + * @returns {Viewer} this + */ + move: function move(offsetX, offsetY) { + var imageData = this.imageData; + this.moveTo(isUndefined(offsetX) ? offsetX : imageData.left + Number(offsetX), isUndefined(offsetY) ? offsetY : imageData.top + Number(offsetY)); + return this; + }, + + /** + * Move the image to an absolute point. + * @param {number} x - The x-axis coordinate. + * @param {number} [y=x] - The y-axis coordinate. + * @returns {Viewer} this + */ + moveTo: function moveTo(x) { + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x; + var imageData = this.imageData; + x = Number(x); + y = Number(y); + + if (this.viewed && !this.played && this.options.movable) { + var changed = false; + + if (isNumber(x)) { + imageData.left = x; + changed = true; + } + + if (isNumber(y)) { + imageData.top = y; + changed = true; + } + + if (changed) { + this.renderImage(); + } + } + + return this; + }, + + /** + * Zoom the image with a relative ratio. + * @param {number} ratio - The target ratio. + * @param {boolean} [hasTooltip=false] - Indicates if it has a tooltip or not. + * @param {Event} [_originalEvent=null] - The original event if any. + * @returns {Viewer} this + */ + zoom: function zoom(ratio) { + var hasTooltip = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var _originalEvent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + var imageData = this.imageData; + ratio = Number(ratio); + + if (ratio < 0) { + ratio = 1 / (1 - ratio); + } else { + ratio = 1 + ratio; + } + + this.zoomTo(imageData.width * ratio / imageData.naturalWidth, hasTooltip, _originalEvent); + return this; + }, + + /** + * Zoom the image to an absolute ratio. + * @param {number} ratio - The target ratio. + * @param {boolean} [hasTooltip=false] - Indicates if it has a tooltip or not. + * @param {Event} [_originalEvent=null] - The original event if any. + * @param {Event} [_zoomable=false] - Indicates if the current zoom is available or not. + * @returns {Viewer} this + */ + zoomTo: function zoomTo(ratio) { + var _this2 = this; + + var hasTooltip = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var _originalEvent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + var _zoomable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var element = this.element, + options = this.options, + pointers = this.pointers, + imageData = this.imageData; + var width = imageData.width, + height = imageData.height, + left = imageData.left, + top = imageData.top, + naturalWidth = imageData.naturalWidth, + naturalHeight = imageData.naturalHeight; + ratio = Math.max(0, ratio); + + if (isNumber(ratio) && this.viewed && !this.played && (_zoomable || options.zoomable)) { + if (!_zoomable) { + var minZoomRatio = Math.max(0.01, options.minZoomRatio); + var maxZoomRatio = Math.min(100, options.maxZoomRatio); + ratio = Math.min(Math.max(ratio, minZoomRatio), maxZoomRatio); + } + + if (_originalEvent && ratio > 0.95 && ratio < 1.05) { + ratio = 1; + } + + var newWidth = naturalWidth * ratio; + var newHeight = naturalHeight * ratio; + var offsetWidth = newWidth - width; + var offsetHeight = newHeight - height; + var oldRatio = width / naturalWidth; + + if (isFunction(options.zoom)) { + addListener(element, EVENT_ZOOM, options.zoom, { + once: true + }); + } + + if (dispatchEvent(element, EVENT_ZOOM, { + ratio: ratio, + oldRatio: oldRatio, + originalEvent: _originalEvent + }) === false) { + return this; + } + + this.zooming = true; + + if (_originalEvent) { + var offset = getOffset(this.viewer); + var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : { + pageX: _originalEvent.pageX, + pageY: _originalEvent.pageY + }; // Zoom from the triggering point of the event + + imageData.left -= offsetWidth * ((center.pageX - offset.left - left) / width); + imageData.top -= offsetHeight * ((center.pageY - offset.top - top) / height); + } else { + // Zoom from the center of the image + imageData.left -= offsetWidth / 2; + imageData.top -= offsetHeight / 2; + } + + imageData.width = newWidth; + imageData.height = newHeight; + imageData.ratio = ratio; + this.renderImage(function () { + _this2.zooming = false; + + if (isFunction(options.zoomed)) { + addListener(element, EVENT_ZOOMED, options.zoomed, { + once: true + }); + } + + dispatchEvent(element, EVENT_ZOOMED, { + ratio: ratio, + oldRatio: oldRatio, + originalEvent: _originalEvent + }); + }); + + if (hasTooltip) { + this.tooltip(); + } + } + + return this; + }, + + /** + * Rotate the image with a relative degree. + * @param {number} degree - The rotate degree. + * @returns {Viewer} this + */ + rotate: function rotate(degree) { + this.rotateTo((this.imageData.rotate || 0) + Number(degree)); + return this; + }, + + /** + * Rotate the image to an absolute degree. + * @param {number} degree - The rotate degree. + * @returns {Viewer} this + */ + rotateTo: function rotateTo(degree) { + var imageData = this.imageData; + degree = Number(degree); + + if (isNumber(degree) && this.viewed && !this.played && this.options.rotatable) { + imageData.rotate = degree; + this.renderImage(); + } + + return this; + }, + + /** + * Scale the image on the x-axis. + * @param {number} scaleX - The scale ratio on the x-axis. + * @returns {Viewer} this + */ + scaleX: function scaleX(_scaleX) { + this.scale(_scaleX, this.imageData.scaleY); + return this; + }, + + /** + * Scale the image on the y-axis. + * @param {number} scaleY - The scale ratio on the y-axis. + * @returns {Viewer} this + */ + scaleY: function scaleY(_scaleY) { + this.scale(this.imageData.scaleX, _scaleY); + return this; + }, + + /** + * Scale the image. + * @param {number} scaleX - The scale ratio on the x-axis. + * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis. + * @returns {Viewer} this + */ + scale: function scale(scaleX) { + var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX; + var imageData = this.imageData; + scaleX = Number(scaleX); + scaleY = Number(scaleY); + + if (this.viewed && !this.played && this.options.scalable) { + var changed = false; + + if (isNumber(scaleX)) { + imageData.scaleX = scaleX; + changed = true; + } + + if (isNumber(scaleY)) { + imageData.scaleY = scaleY; + changed = true; + } + + if (changed) { + this.renderImage(); + } + } + + return this; + }, + + /** + * Play the images + * @param {boolean} [fullscreen=false] - Indicate if request fullscreen or not. + * @returns {Viewer} this + */ + play: function play() { + var _this3 = this; + + var fullscreen = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + if (!this.isShown || this.played) { + return this; + } + + var options = this.options, + player = this.player; + var onLoad = this.loadImage.bind(this); + var list = []; + var total = 0; + var index = 0; + this.played = true; + this.onLoadWhenPlay = onLoad; + + if (fullscreen) { + this.requestFullscreen(); + } + + addClass(player, CLASS_SHOW); + forEach(this.items, function (item, i) { + var img = item.querySelector('img'); + var image = document.createElement('img'); + image.src = getData(img, 'originalUrl'); + image.alt = img.getAttribute('alt'); + total += 1; + addClass(image, CLASS_FADE); + toggleClass(image, CLASS_TRANSITION, options.transition); + + if (hasClass(item, CLASS_ACTIVE)) { + addClass(image, CLASS_IN); + index = i; + } + + list.push(image); + addListener(image, EVENT_LOAD, onLoad, { + once: true + }); + player.appendChild(image); + }); + + if (isNumber(options.interval) && options.interval > 0) { + var play = function play() { + _this3.playing = setTimeout(function () { + removeClass(list[index], CLASS_IN); + index += 1; + index = index < total ? index : 0; + addClass(list[index], CLASS_IN); + play(); + }, options.interval); + }; + + if (total > 1) { + play(); + } + } + + return this; + }, + // Stop play + stop: function stop() { + var _this4 = this; + + if (!this.played) { + return this; + } + + var player = this.player; + this.played = false; + clearTimeout(this.playing); + forEach(player.getElementsByTagName('img'), function (image) { + removeListener(image, EVENT_LOAD, _this4.onLoadWhenPlay); + }); + removeClass(player, CLASS_SHOW); + player.innerHTML = ''; + this.exitFullscreen(); + return this; + }, + // Enter modal mode (only available in inline mode) + full: function full() { + var _this5 = this; + + var options = this.options, + viewer = this.viewer, + image = this.image, + list = this.list; + + if (!this.isShown || this.played || this.fulled || !options.inline) { + return this; + } + + this.fulled = true; + this.open(); + addClass(this.button, CLASS_FULLSCREEN_EXIT); + + if (options.transition) { + removeClass(list, CLASS_TRANSITION); + + if (this.viewed) { + removeClass(image, CLASS_TRANSITION); + } + } + + addClass(viewer, CLASS_FIXED); + viewer.setAttribute('style', ''); + setStyle(viewer, { + zIndex: options.zIndex + }); + this.initContainer(); + this.viewerData = assign({}, this.containerData); + this.renderList(); + + if (this.viewed) { + this.initImage(function () { + _this5.renderImage(function () { + if (options.transition) { + setTimeout(function () { + addClass(image, CLASS_TRANSITION); + addClass(list, CLASS_TRANSITION); + }, 0); + } + }); + }); + } + + return this; + }, + // Exit modal mode (only available in inline mode) + exit: function exit() { + var _this6 = this; + + var options = this.options, + viewer = this.viewer, + image = this.image, + list = this.list; + + if (!this.isShown || this.played || !this.fulled || !options.inline) { + return this; + } + + this.fulled = false; + this.close(); + removeClass(this.button, CLASS_FULLSCREEN_EXIT); + + if (options.transition) { + removeClass(list, CLASS_TRANSITION); + + if (this.viewed) { + removeClass(image, CLASS_TRANSITION); + } + } + + removeClass(viewer, CLASS_FIXED); + setStyle(viewer, { + zIndex: options.zIndexInline + }); + this.viewerData = assign({}, this.parentData); + this.renderViewer(); + this.renderList(); + + if (this.viewed) { + this.initImage(function () { + _this6.renderImage(function () { + if (options.transition) { + setTimeout(function () { + addClass(image, CLASS_TRANSITION); + addClass(list, CLASS_TRANSITION); + }, 0); + } + }); + }); + } + + return this; + }, + // Show the current ratio of the image with percentage + tooltip: function tooltip() { + var _this7 = this; + + var options = this.options, + tooltipBox = this.tooltipBox, + imageData = this.imageData; + + if (!this.viewed || this.played || !options.tooltip) { + return this; + } + + tooltipBox.textContent = "".concat(Math.round(imageData.ratio * 100), "%"); + + if (!this.tooltipping) { + if (options.transition) { + if (this.fading) { + dispatchEvent(tooltipBox, EVENT_TRANSITION_END); + } + + addClass(tooltipBox, CLASS_SHOW); + addClass(tooltipBox, CLASS_FADE); + addClass(tooltipBox, CLASS_TRANSITION); // Force reflow to enable CSS3 transition + + tooltipBox.initialOffsetWidth = tooltipBox.offsetWidth; + addClass(tooltipBox, CLASS_IN); + } else { + addClass(tooltipBox, CLASS_SHOW); + } + } else { + clearTimeout(this.tooltipping); + } + + this.tooltipping = setTimeout(function () { + if (options.transition) { + addListener(tooltipBox, EVENT_TRANSITION_END, function () { + removeClass(tooltipBox, CLASS_SHOW); + removeClass(tooltipBox, CLASS_FADE); + removeClass(tooltipBox, CLASS_TRANSITION); + _this7.fading = false; + }, { + once: true + }); + removeClass(tooltipBox, CLASS_IN); + _this7.fading = true; + } else { + removeClass(tooltipBox, CLASS_SHOW); + } + + _this7.tooltipping = false; + }, 1000); + return this; + }, + // Toggle the image size between its natural size and initial size + toggle: function toggle() { + if (this.imageData.ratio === 1) { + this.zoomTo(this.initialImageData.ratio, true); + } else { + this.zoomTo(1, true); + } + + return this; + }, + // Reset the image to its initial state + reset: function reset() { + if (this.viewed && !this.played) { + this.imageData = assign({}, this.initialImageData); + this.renderImage(); + } + + return this; + }, + // Update viewer when images changed + update: function update() { + var element = this.element, + options = this.options, + isImg = this.isImg; // Destroy viewer if the target image was deleted + + if (isImg && !element.parentNode) { + return this.destroy(); + } + + var images = []; + forEach(isImg ? [element] : element.querySelectorAll('img'), function (image) { + if (options.filter) { + if (options.filter(image)) { + images.push(image); + } + } else { + images.push(image); + } + }); + + if (!images.length) { + return this; + } + + this.images = images; + this.length = images.length; + + if (this.ready) { + var indexes = []; + forEach(this.items, function (item, i) { + var img = item.querySelector('img'); + var image = images[i]; + + if (image && img) { + if (image.src !== img.src) { + indexes.push(i); + } + } else { + indexes.push(i); + } + }); + setStyle(this.list, { + width: 'auto' + }); + this.initList(); + + if (this.isShown) { + if (this.length) { + if (this.viewed) { + var index = indexes.indexOf(this.index); + + if (index >= 0) { + this.viewed = false; + this.view(Math.max(this.index - (index + 1), 0)); + } else { + addClass(this.items[this.index], CLASS_ACTIVE); + } + } + } else { + this.image = null; + this.viewed = false; + this.index = 0; + this.imageData = {}; + this.canvas.innerHTML = ''; + this.title.innerHTML = ''; + } + } + } else { + this.build(); + } + + return this; + }, + // Destroy the viewer + destroy: function destroy() { + var element = this.element, + options = this.options; + + if (!element[NAMESPACE]) { + return this; + } + + this.destroyed = true; + + if (this.ready) { + if (this.played) { + this.stop(); + } + + if (options.inline) { + if (this.fulled) { + this.exit(); + } + + this.unbind(); + } else if (this.isShown) { + if (this.viewing) { + if (this.imageRendering) { + this.imageRendering.abort(); + } else if (this.imageInitializing) { + this.imageInitializing.abort(); + } + } + + if (this.hiding) { + this.transitioning.abort(); + } + + this.hidden(); + } else if (this.showing) { + this.transitioning.abort(); + this.hidden(); + } + + this.ready = false; + this.viewer.parentNode.removeChild(this.viewer); + } else if (options.inline) { + if (this.delaying) { + this.delaying.abort(); + } else if (this.initializing) { + this.initializing.abort(); + } + } + + if (!options.inline) { + removeListener(element, EVENT_CLICK, this.onStart); + } + + element[NAMESPACE] = undefined; + return this; + } + }; + + var others = { + open: function open() { + var body = this.body; + addClass(body, CLASS_OPEN); + body.style.paddingRight = "".concat(this.scrollbarWidth + (parseFloat(this.initialBodyPaddingRight) || 0), "px"); + }, + close: function close() { + var body = this.body; + removeClass(body, CLASS_OPEN); + body.style.paddingRight = this.initialBodyPaddingRight; + }, + shown: function shown() { + var element = this.element, + options = this.options; + this.fulled = true; + this.isShown = true; + this.render(); + this.bind(); + this.showing = false; + + if (isFunction(options.shown)) { + addListener(element, EVENT_SHOWN, options.shown, { + once: true + }); + } + + if (dispatchEvent(element, EVENT_SHOWN) === false) { + return; + } + + if (this.ready && this.isShown && !this.hiding) { + this.view(this.index); + } + }, + hidden: function hidden() { + var element = this.element, + options = this.options; + this.fulled = false; + this.viewed = false; + this.isShown = false; + this.close(); + this.unbind(); + addClass(this.viewer, CLASS_HIDE); + this.resetList(); + this.resetImage(); + this.hiding = false; + + if (!this.destroyed) { + if (isFunction(options.hidden)) { + addListener(element, EVENT_HIDDEN, options.hidden, { + once: true + }); + } + + dispatchEvent(element, EVENT_HIDDEN); + } + }, + requestFullscreen: function requestFullscreen() { + var document = this.element.ownerDocument; + + if (this.fulled && !(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement)) { + var documentElement = document.documentElement; // Element.requestFullscreen() + + if (documentElement.requestFullscreen) { + documentElement.requestFullscreen(); + } else if (documentElement.webkitRequestFullscreen) { + documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); + } else if (documentElement.mozRequestFullScreen) { + documentElement.mozRequestFullScreen(); + } else if (documentElement.msRequestFullscreen) { + documentElement.msRequestFullscreen(); + } + } + }, + exitFullscreen: function exitFullscreen() { + var document = this.element.ownerDocument; + + if (this.fulled && (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement)) { + // Document.exitFullscreen() + if (document.exitFullscreen) { + document.exitFullscreen(); + } else if (document.webkitExitFullscreen) { + document.webkitExitFullscreen(); + } else if (document.mozCancelFullScreen) { + document.mozCancelFullScreen(); + } else if (document.msExitFullscreen) { + document.msExitFullscreen(); + } + } + }, + change: function change(event) { + var options = this.options, + pointers = this.pointers; + var pointer = pointers[Object.keys(pointers)[0]]; + var offsetX = pointer.endX - pointer.startX; + var offsetY = pointer.endY - pointer.startY; + + switch (this.action) { + // Move the current image + case ACTION_MOVE: + this.move(offsetX, offsetY); + break; + // Zoom the current image + + case ACTION_ZOOM: + this.zoom(getMaxZoomRatio(pointers), false, event); + break; + + case ACTION_SWITCH: + { + this.action = 'switched'; + var absoluteOffsetX = Math.abs(offsetX); + + if (absoluteOffsetX > 1 && absoluteOffsetX > Math.abs(offsetY)) { + // Empty `pointers` as `touchend` event will not be fired after swiped in iOS browsers. + this.pointers = {}; + + if (offsetX > 1) { + this.prev(options.loop); + } else if (offsetX < -1) { + this.next(options.loop); + } + } + + break; + } + } // Override + + + forEach(pointers, function (p) { + p.startX = p.endX; + p.startY = p.endY; + }); + }, + isSwitchable: function isSwitchable() { + var imageData = this.imageData, + viewerData = this.viewerData; + return this.length > 1 && imageData.left >= 0 && imageData.top >= 0 && imageData.width <= viewerData.width && imageData.height <= viewerData.height; + } + }; + + var AnotherViewer = WINDOW.Viewer; + + var Viewer = + /*#__PURE__*/ + function () { + /** + * Create a new Viewer. + * @param {Element} element - The target element for viewing. + * @param {Object} [options={}] - The configuration options. + */ + function Viewer(element) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, Viewer); + + if (!element || element.nodeType !== 1) { + throw new Error('The first argument is required and must be an element.'); + } + + this.element = element; + this.options = assign({}, DEFAULTS, isPlainObject(options) && options); + this.action = false; + this.fading = false; + this.fulled = false; + this.hiding = false; + this.imageClicked = false; + this.imageData = {}; + this.index = this.options.initialViewIndex; + this.isImg = false; + this.isShown = false; + this.length = 0; + this.played = false; + this.playing = false; + this.pointers = {}; + this.ready = false; + this.showing = false; + this.timeout = false; + this.tooltipping = false; + this.viewed = false; + this.viewing = false; + this.wheeling = false; + this.zooming = false; + this.init(); + } + + _createClass(Viewer, [{ + key: "init", + value: function init() { + var _this = this; + + var element = this.element, + options = this.options; + + if (element[NAMESPACE]) { + return; + } + + element[NAMESPACE] = this; + var isImg = element.tagName.toLowerCase() === 'img'; + var images = []; + forEach(isImg ? [element] : element.querySelectorAll('img'), function (image) { + if (isFunction(options.filter)) { + if (options.filter.call(_this, image)) { + images.push(image); + } + } else { + images.push(image); + } + }); + this.isImg = isImg; + this.length = images.length; + this.images = images; + var ownerDocument = element.ownerDocument; + var body = ownerDocument.body || ownerDocument.documentElement; + this.body = body; + this.scrollbarWidth = window.innerWidth - ownerDocument.documentElement.clientWidth; + this.initialBodyPaddingRight = window.getComputedStyle(body).paddingRight; // Override `transition` option if it is not supported + + if (isUndefined(document.createElement(NAMESPACE).style.transition)) { + options.transition = false; + } + + if (options.inline) { + var count = 0; + + var progress = function progress() { + count += 1; + + if (count === _this.length) { + var timeout; + _this.initializing = false; + _this.delaying = { + abort: function abort() { + clearTimeout(timeout); + } + }; // build asynchronously to keep `this.viewer` is accessible in `ready` event handler. + + timeout = setTimeout(function () { + _this.delaying = false; + + _this.build(); + }, 0); + } + }; + + this.initializing = { + abort: function abort() { + forEach(images, function (image) { + if (!image.complete) { + removeListener(image, EVENT_LOAD, progress); + } + }); + } + }; + forEach(images, function (image) { + if (image.complete) { + progress(); + } else { + addListener(image, EVENT_LOAD, progress, { + once: true + }); + } + }); + } else { + addListener(element, EVENT_CLICK, this.onStart = function (_ref) { + var target = _ref.target; + + if (target.tagName.toLowerCase() === 'img' && (!isFunction(options.filter) || options.filter.call(_this, target))) { + _this.view(_this.images.indexOf(target)); + } + }); + } + } + }, { + key: "build", + value: function build() { + if (this.ready) { + return; + } + + var element = this.element, + options = this.options; + var parent = element.parentNode; + var template = document.createElement('div'); + template.innerHTML = TEMPLATE; + var viewer = template.querySelector(".".concat(NAMESPACE, "-container")); + var title = viewer.querySelector(".".concat(NAMESPACE, "-title")); + var toolbar = viewer.querySelector(".".concat(NAMESPACE, "-toolbar")); + var navbar = viewer.querySelector(".".concat(NAMESPACE, "-navbar")); + var button = viewer.querySelector(".".concat(NAMESPACE, "-button")); + var canvas = viewer.querySelector(".".concat(NAMESPACE, "-canvas")); + this.parent = parent; + this.viewer = viewer; + this.title = title; + this.toolbar = toolbar; + this.navbar = navbar; + this.button = button; + this.canvas = canvas; + this.footer = viewer.querySelector(".".concat(NAMESPACE, "-footer")); + this.tooltipBox = viewer.querySelector(".".concat(NAMESPACE, "-tooltip")); + this.player = viewer.querySelector(".".concat(NAMESPACE, "-player")); + this.list = viewer.querySelector(".".concat(NAMESPACE, "-list")); + addClass(title, !options.title ? CLASS_HIDE : getResponsiveClass(Array.isArray(options.title) ? options.title[0] : options.title)); + addClass(navbar, !options.navbar ? CLASS_HIDE : getResponsiveClass(options.navbar)); + toggleClass(button, CLASS_HIDE, !options.button); + + if (options.backdrop) { + addClass(viewer, "".concat(NAMESPACE, "-backdrop")); + + if (!options.inline && options.backdrop !== 'static') { + setData(canvas, DATA_ACTION, 'hide'); + } + } + + if (isString(options.className) && options.className) { + // In case there are multiple class names + options.className.split(REGEXP_SPACES).forEach(function (className) { + addClass(viewer, className); + }); + } + + if (options.toolbar) { + var list = document.createElement('ul'); + var custom = isPlainObject(options.toolbar); + var zoomButtons = BUTTONS.slice(0, 3); + var rotateButtons = BUTTONS.slice(7, 9); + var scaleButtons = BUTTONS.slice(9); + + if (!custom) { + addClass(toolbar, getResponsiveClass(options.toolbar)); + } + + forEach(custom ? options.toolbar : BUTTONS, function (value, index) { + var deep = custom && isPlainObject(value); + var name = custom ? hyphenate(index) : value; + var show = deep && !isUndefined(value.show) ? value.show : value; + + if (!show || !options.zoomable && zoomButtons.indexOf(name) !== -1 || !options.rotatable && rotateButtons.indexOf(name) !== -1 || !options.scalable && scaleButtons.indexOf(name) !== -1) { + return; + } + + var size = deep && !isUndefined(value.size) ? value.size : value; + var click = deep && !isUndefined(value.click) ? value.click : value; + var item = document.createElement('li'); + item.setAttribute('role', 'button'); + addClass(item, "".concat(NAMESPACE, "-").concat(name)); + + if (!isFunction(click)) { + setData(item, DATA_ACTION, name); + } + + if (isNumber(show)) { + addClass(item, getResponsiveClass(show)); + } + + if (['small', 'large'].indexOf(size) !== -1) { + addClass(item, "".concat(NAMESPACE, "-").concat(size)); + } else if (name === 'play') { + addClass(item, "".concat(NAMESPACE, "-large")); + } + + if (isFunction(click)) { + addListener(item, EVENT_CLICK, click); + } + + list.appendChild(item); + }); + toolbar.appendChild(list); + } else { + addClass(toolbar, CLASS_HIDE); + } + + if (!options.rotatable) { + var rotates = toolbar.querySelectorAll('li[class*="rotate"]'); + addClass(rotates, CLASS_INVISIBLE); + forEach(rotates, function (rotate) { + toolbar.appendChild(rotate); + }); + } + + if (options.inline) { + addClass(button, CLASS_FULLSCREEN); + setStyle(viewer, { + zIndex: options.zIndexInline + }); + + if (window.getComputedStyle(parent).position === 'static') { + setStyle(parent, { + position: 'relative' + }); + } + + parent.insertBefore(viewer, element.nextSibling); + } else { + addClass(button, CLASS_CLOSE); + addClass(viewer, CLASS_FIXED); + addClass(viewer, CLASS_FADE); + addClass(viewer, CLASS_HIDE); + setStyle(viewer, { + zIndex: options.zIndex + }); + var container = options.container; + + if (isString(container)) { + container = element.ownerDocument.querySelector(container); + } + + if (!container) { + container = this.body; + } + + container.appendChild(viewer); + } + + if (options.inline) { + this.render(); + this.bind(); + this.isShown = true; + } + + this.ready = true; + + if (isFunction(options.ready)) { + addListener(element, EVENT_READY, options.ready, { + once: true + }); + } + + if (dispatchEvent(element, EVENT_READY) === false) { + this.ready = false; + return; + } + + if (this.ready && options.inline) { + this.view(this.index); + } + } + /** + * Get the no conflict viewer class. + * @returns {Viewer} The viewer class. + */ + + }], [{ + key: "noConflict", + value: function noConflict() { + window.Viewer = AnotherViewer; + return Viewer; + } + /** + * Change the default options. + * @param {Object} options - The new default options. + */ + + }, { + key: "setDefaults", + value: function setDefaults(options) { + assign(DEFAULTS, isPlainObject(options) && options); + } + }]); + + return Viewer; + }(); + + assign(Viewer.prototype, render, events, handlers, methods, others); + + return Viewer; + +}))); diff --git a/template/404.html b/template/404.html index 68c1619..0c1977c 100644 --- a/template/404.html +++ b/template/404.html @@ -13,9 +13,6 @@
- - -

返回首页

diff --git a/template/app_doc/create_base.html b/template/app_doc/create_base.html index a73ad19..a67bed7 100644 --- a/template/app_doc/create_base.html +++ b/template/app_doc/create_base.html @@ -26,6 +26,31 @@ .markdown-body ol ol ul,.markdown-body ol ul ul,.markdown-body ul ol ul,.markdown-body ul ul ul li{ list-style-type: square; } + .select-img-list{ + cursor: pointer; + position: relative; + display:flex; + float: left; + align-items:center; + width: 120px; + height:120px; + margin: 0 20px 30px 0; + text-align: center; + overflow: hidden; + } + + .select-img-list:hover{ + background-color: #EAFFEA; + } + .select-img-list-i{ + display: block; + width: 100%; + height: auto; + -webkit-background-size: contain; + border: 1px solid transparent; + border-radius: 3px; + overflow: hidden; + } + {% endif %} {% endblock %} {% block content_head %}

{{ doc.name }}


+

+ 作者:{{ doc.create_user.username }}      最后修改于:{{ doc.modify_time }} -

+ {% endblock %} {% block page_content %} {# {{ doc.content | safe }} #} - - + + {% endblock %} {% block doc_previous_next %} @@ -56,4 +56,23 @@ {% endif %}
+{% endblock %} + +{% block custom_script %} + {% endblock %} \ No newline at end of file diff --git a/template/app_doc/docs_base.html b/template/app_doc/docs_base.html index 5f2d3aa..d65b450 100644 --- a/template/app_doc/docs_base.html +++ b/template/app_doc/docs_base.html @@ -40,7 +40,20 @@ } /* 下拉目录隐藏li样式 */ .editormd-toc-menu ul.markdown-toc-list li{ - list-style:none; + /*list-style:none;*/ + } + /* 弹出框文档目录样式 */ + ul.markdown-toc-list{ + list-style-position:inside; + } + ul.markdown-toc-list li{ + list-style: inherit!important; + } + ul.markdown-toc-list > li > ul > li,ul.markdown-toc-list > li > ul li{ + padding-left:10px; + } + ul.markdown-toc-list a{ + text-decoration: underline!important; } - -
-
-
+ {% block doc_previous_next %}{% endblock %}