首次提交

This commit is contained in:
FH
2025-04-21 15:56:25 +08:00
parent dce4c66dc7
commit 060a17a5f8
48 changed files with 7436 additions and 4 deletions
+8
View File
@@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.11" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+24
View File
@@ -0,0 +1,24 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="5">
<item index="0" class="java.lang.String" itemvalue="jinja2" />
<item index="1" class="java.lang.String" itemvalue="fastapi" />
<item index="2" class="java.lang.String" itemvalue="starlette" />
<item index="3" class="java.lang.String" itemvalue="python-multipart" />
<item index="4" class="java.lang.String" itemvalue="uvicorn" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="SpellCheckingInspection" enabled="true" level="TYPO" enabled_by_default="true">
<option name="processCode" value="false" />
<option name="processLiterals" value="true" />
<option name="processComments" value="false" />
</inspection_tool>
</profile>
</component>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/001-Study.iml" filepath="$PROJECT_DIR$/.idea/001-Study.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
print("1", "2", "3", sep="haha", end="不换行") # ,代表间隔符;sep代表间隔的符号;end代表结束符,默认是换行符/n
print("1")
"""
点击函数后会弹出函数文档,或者按Ctrl+Q,或者按右键“转到”
如果需要翻译则安装Translation插件
"""
+7
View File
@@ -0,0 +1,7 @@
a = "1"
print(a) # 不加引号打印变量值
print("a") # 加引号打印字符串
# ============================================================
(b) = 2
print(b) # 标识符被包含在括号内,对标识符本身没有影响,仍然可以打印
# 标识符:对变量名、函数名的定义符,例如上面的变量名a和(b)
@@ -0,0 +1,43 @@
# Python的数值类型分为四种:整型int、浮点型float、复数complex和布尔型bool。
a = 1
print(type(a)) # 检测数据类型的方法是type()
# ============================================================
bool1 = True # =1
bool2 = False # =0
print(type(bool1), type(bool2))
# ============================================================
ma = 1 + 2j # 1是实部,2是虚部,j是虚数单位
print(type(ma))
# ============================================================
# 字符串(str)也就是string
a = "1" # 字符串需要加引号
print(a)
# ============================================================
# 占位符有三种方式%、format()和f-string
# %是格式化占位符,格式化输出
a = "hello"
b = 30
print("我的名字是%s" % a, "我的年龄是%d" % b) # %s:用于插入字符串, %d:用于插入整数
print("我的名字是%s" % a, "," "我的年龄是%d" % b) # 名字和年龄之间用逗号隔开
print("我的名字是%s,我的年龄是%d" % (a, b)) # 一次性格式化生成完整的字符串
# ============================================================
# %d可以设置位数,例如:%5d,不足位数前面补空白
a = 123
print("%5d" % a) # 右对齐,宽度为5
print("%-5d" % a) # 左对齐,宽度为5
print("%05d" % a) # 宽度为5,不足前面补0
print("%+5d" % a) # 宽度为5,前缀为+
# ============================================================
# %f浮点数
a = 1.2
print("%f" % a) # 默认后六位小数,遵循四舍五入原则
print("%.5f" % a) # 小数点后5位
print("%+.5f" % a) # 前缀为+,小数点后5位
# ============================================================
# %%代表百分号
print("我是%%" % ())
# ============================================================
# f-string格式化
a = "1"
b = 30
print(f"我的名字是{a},我的年龄是{b}") # 变量值加花括号,前面加f
@@ -0,0 +1,62 @@
print("hello world")
# ============================================================
"""
算数:
加法:+
减法:-
乘法:*
除法:/ 除法的商一定是浮点数,除数不能为0,左边是被除数,右边是除数
整除:// 取商的整数部分(取整除),向下取整,不遵循五入的原则,后面有小数就忽略小数,其中若有浮点数,结果也是浮点数
取余: % 也叫取模
取幂:**
计算优先级:幂>乘>除>取余>取整除>加减
"""
print(5 / 1) # 除法的商一定是浮点数,例如5/1=5.0
print(5 // 2) # 取商的整数部分,向下取整,不遵循五入的原则,后面有小数就忽略小数,=2
print(5 % 2) # 取余数,5/2=2.5,商是2,2*2=4,余数是5-4=1
print(2 ** 2) # 取幂,2的2次方=4
# ============================================================
"""
赋值运算符:
仅针对变量计算
= #非常简单
+= #a = a+1即是a += 1,+=包含了运算和赋值,即将左边的值等于值+1,随后赋给左边的值
-= #a = a-1即是a -= 1
*= #a = a*1即是a *= 1
/= #a = a/1即是a /= 1
"""
a = 5
a += 5 # a = a+5
print(a)
a -= 5 # a = a-5
print(a)
a *= 5 # a = a*5
print(a)
a /= 5 # a = a/5
print(a)
# ============================================================
"""
输入函数:
input()
函数签名:def input(__prompt: object = ...) -> str 接受一个prompt参数(字符串格式),即是提示的意思,会在控制台中显示
"""
input("请输入:") # 本质上是调用input函数
a = input("请再次输入:") # 可以赋值给变量
print(a)
# ============================================================
"""
转义字符:
\t # 制表符,制表符是一种 空白字符,主要用于文本的对齐。它不像普通的空格那样占用固定宽度,制表符通常会把文本“跳”到下一个 Tab 停止位。这个跳转的距离通常是 4 到 8 个空格,但具体的表现可能取决于编辑器或程序的配置
\n # 换行符
\r # 将当前位置移到本行开头
\\ # 表示一个\
r # 原生字符串,取消转义
"""
print("西门吹雪\t5岁\t美国") # 制表符
print("张三李四啊\t100岁\t中国") # 制表符
print("zhangsan\t5\tUSA") # 制表符
print("lisi\t100\tChina") # 制表符
print("hello\nworld") # 换行符
print("hello\rworld") # 将当前位置移到本行开头
print("hello\\\\world") # 两个\\表示一个\
print(r"hello\\\\world") # 原生字符串,取消转义
@@ -0,0 +1,49 @@
print("hello world")
# ============================================================
"""
1、比较运算符:
== # 比较两个值是否相等,相等返回真,不相等返回为假
!= # 比较两个值是否不相等,不相等返回真,相等返回为假
>
<
>=
<=
"""
a = 100
b = 200
print(a == b) # a是否等于b
print(a != b) # a是否不等于b
print(a > b) # a是否大于b
print(a < b) # a是否小于b
print(a >= b) # a是否大于等于b
print(a <= b) # a是否小于等于b
# ============================================================
"""
2、逻辑运算符:
and # 与,如果两个条件都为真,则返回真,否则返回假
or # 或,如果两个条件有一个为真,则返回真,否则返回假
not # 非,取反,如果为真则返回假,为假则返回真
"""
a = 100
b = 200
c = 300
print(a < b and c > a) # a是否大于b,b是否大于a,如果两个条件都为真,则返回真,否则返回假
print(a > b or b > a) # a是否大于b,b是否大于a,如果两个条件有一个为真,则返回真,否则返回假
print(not a > b) # 取反,如果为真则返回假,为假则返回真
# ============================================================
"""
3、if #判断,条件后加:
:的作用:表示代码块的开始,起到代码块的结构化,与其他语言的{}类似
定义函数时的:也意味着接下来的缩进代码也是这个函数的内容
"""
a = "10" # 字符串类型
if a > "5": # 字符串类型的比较,不是数字比较,而是逐个字符按照他们的ASCII码值比较
print("a大于5")
else:
print("a小于5") # 10的第一个字符是1,ASCII码值是49,5的ASCII码值是53,所以输出a小于5
a = 10 # 整数类型
if a > 5: # 整数类型比较,直接比较
print("a大于5")
else:
print("a小于5")
@@ -0,0 +1,49 @@
print("hello world")
# ============================================================
"""
1、if-else:
if:代码块下执行满足条件要做的事情
else:代码块下执行不满足条件要做的事情,else后面不要追加任何判断条件
"""
a = 10
if a > 5: # 条件为真
print("a大于5") # 执行
else: # 条件为假
print("a小于5") # 不执行
# ============================================================
"""
2、if-elif:
if:代码块下执行满足条件1要做的事情
elif:代码块下执行满足其他条件要做的事情,elif后面要追加判断条件
如果满足任何一个if或者elif条件,那么后面的if或者elif都不执行
"""
b = 10
if b > 20: # 条件为假
print("b大于20") # 不执行
elif b < 20: # 条件为真
print("b小于20") # 执行
else: # 以上条件全部为假时执行此代码块的语句
print("b等于20")
# ============================================================
"""
3、if嵌套
if里面有if
"""
c = 10
if c > 5: # 条件为真
print("c大于5") # 执行
if c < 15: # 继续向下执行代码,条件为真
print("c小于15") # 执行
else: # 条件为假
print("c大于15") # 不执行
else: # 如果以上判断都为假,则执行此代码块的语句
print("c小于5")
# ============================================================
"""
4、三目运算(三元运算):
涉及三个操部分:
真时返回的值:条件为真的时候返回的结果。
条件:判断条件的真假。
假时返回的值:条件为假的时候返回的结果。
"""
print("a大于5") if a > 5 else print("a小于5")
@@ -0,0 +1,113 @@
print("hello world")
# ============================================================
"""
1、循环语句:
循环语句用于重复执行某段代码,直到满足某个条件为止
应当正确改变变量,使条件满足,避免死循环
"""
# ============================================================
"""
2、while循环:
while循环在某个条件为 真 的情况下,不断执行循环体中的代码,直到条件变为 假
while True: 死循环,用法:作为长期运行的任务、持续等待用户输入、不断尝试操作直到成功、游戏循环、 事件循环、需要后台运行的服务
如何终止死循环?:通过 break 来打破循环、户通过输入特定的指令、捕获异常(如网络连接中断、用户中止等)、操作系统的信号来终止死循环(如 Ctrl+C 发送的中断信号)
while循环嵌套: 一个while循环里还有一个while循环
"""
# 格式
i = 0 # 初始化,表示从0开始
while i <= 5: # 定义条件
print(i) # 循环体,当前条件为真,执行循环体
i += 1 # 随后变量自增(改变变量),本质上是i = i + 1;如果不改变变量,则进入死循环
# 死循环示例
while False: # 条件永远为假,不进入死循环;如果是True或者除了0和False的值,则会执行循环体
print("hello world")
# 小案例:计算1到100的和
i = 1 # 初始化, 表示从1开始计算
s = 0 # 初始化,用于计算和
while i <= 100: # 定义条件
s += i # 循环体,s = s + i, 计算和
i += 1 # 变量自增
print(s)
# while循环嵌套,每执行一次外循环,内循环在条件满足的情况下会一直循环
i = 1 # 定义一个记录外部循环次数的变量
while i <= 3: # 外部循环,控制循环次数
print("第%d次外循环" % i) # %d表示格式化输出,用于插入整数
j = 1 # 定义一个记录内部循环次数的变量
while j <= 5: # 内部循环,控制循环次数
print("第%d次内循环" % j)
j += 1 # 变量自增
i += 1
# ============================================================
"""
3、for循环(迭代循环):
for 循环用于遍历(迭代)一个序列(如列表、元组、字符串、字典)或可迭代对象中的每一个元素,并对每个元素执行一段代码。
可以用于依次取出对象中的元素
相比while,for循环更简洁,更易读,更易理解,更易维护,更易扩展。
"""
# 简单格式
str1 = "hello world" # 定义一个字符串变量,作为可迭代对象
for i in str1: # i是临时变量,遍历可迭代对象中的每一个字符存储在i中,可以自定义
print(i) # 循环体,循环打印字符串中的每一个字符
# 其他格式1(引入了range()函数)
for i in range(1, 6): # range()函数可接受三个参数:range(start, stop, step),从start开始1,到stop结束6,步长step默认为1;返回值不包含stop,即1,2,3,4,5
print(i) # 循环体,循环打印1到5
# 其他格式2(引入了range()函数,但是不写参数)
for i in range(5): # 循环次数等于从0开始直到填写的数字5,start参数默认为0,所以range(5) 等价于 range(0, 5)
print(i) # 循环体,循环打印0到4
# 其他格式3(不打印i值,循环执行其他代码)
for i in range(5):
print("hello world") # 循环体,循环打印5次
# 其他格式4(不关心循环变量的值,只关心循环次数)
for _ in range(5): # 用下划线_代替临时变量i,表示不关心循环变量的值,只关心循环次数
print("hello world") # 循环体,循环打印5次
# 小案例:计算1到100的和
s = 0 # 初始化,用于计算和
for i in range(1, 101): # 从1到100
s += i # 每次循环,将i加到s中
print(s)
# ============================================================
"""
4、break和continue:
break:在循环中遇到 break 时,立即终止整个循环。
break只在循环中起作用,即便是在if代码块下,也会立即终止if所在的循环体
如果有循环嵌套,且break在内循环,那么只影响内部的循环,不会终止外部循环
continue:跳过本次循环的剩余部分,直接开始下一次循环。
continue只在循环中起作用,即便是在if代码块下,也会立即中止if所在的循环体的剩余部分
如果有循环嵌套,且continue在内循环,那么只影响内部的循环,不会跳到外部循环的开头
他们只能放在循环内
"""
# break示例1(规范写法, 主要在变量i的自增位置, 更加清晰)
i = 1 # 初始化, 表示从1开始
while i <= 5: # 定义条件
print("我在吃第%d个苹果" % i)
if i == 3: # 条件为真,执行循环体,并跳出循环
print("吃饱了,不吃了") # 循环体
break # 跳出当前while循环
i += 1 # 变量自增
# break示例2(不太规范的写法,变量i的自增位置在if循环之前, 不方便阅读和逻辑不清晰)
i = 1
while i <= 5:
print("我在吃第%d个苹果" % i)
i += 1
if i > 3:
print("吃饱了,不吃了")
break
# continue示例1(与break不同,变量i的自增需要在continue之前)
i = 1 # 初始化, 表示从1开始
while i <= 5: # 定义条件
print("我在吃第%d个苹果" % i)
if i == 3: # 条件为真,执行循环体
print("发现坏了,第%d个不吃了" % i)
i += 1 # 变量自增
continue # 跳过当前while循环的剩余部分,直接开始下一次循环
i += 1 # 变量自增
@@ -0,0 +1,57 @@
print("hello world")
# ============================================================
"""
字符串编码:
本质上就是二进制数据与语言文字的一一对应关系
"""
# ============================================================
"""
1、ASCII编码
表示英语及西欧语言,占8bit/1bytes
只能表示少量的字母和数字
2、GB2312
国家简体中文字符集,兼容ASCII,占2bytes
可以表示中文
3、Unicode编码
国际标准组织统一标准字符集,占2bytes
可以显示各种字符,字符与数字之间的转换速度更快一些
但是占用存储空间较大
4、GBK编码
GB2312的扩展字符集,支持繁体字,兼容GB2312,占2bytes
5、UTF-8编码
不定长编码,占1-3bytes
把不同的字符用不同的长度表示,节约存储空间,比较常用
字符与数字的转换速度较慢,每次都需要计算字符需要多少个字节来表示
"""
# ============================================================
"""
1、字符串编码转换
bytes以字节为单位进行处理
对于bytes,只需要知道他跟字符串类型之间的相互转换
应用场景:
网络传输数据时通常会将字符串编码为**bytes**,如 HTTP 请求和响应中的数据
发送 JSON 数据时需要先将其编码为 UTF-8 字节,再通过网络传输
读写文本文件时需要指定正确的编码格式
在存储和查询数据库时,需要确保数据的编码一致性,避免出现乱码问题
编码不仅限于字符处理,还涉及数据压缩与加密算法的实现。例如,某些压缩算法会将数据处理为字节流进行编码。
"""
# 1. 编码:将字符串转换为字节,引入encode()函数,此函数接受一个字符串参数,返回一个bytes对象
a = "你好,世界" # 包含中文的字符串
print(type(a)) # 打印类型
a1 = a.encode("utf-8") # 编码为 utf-8 字节序列
print(a1) # 输出编码: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
print(type(a1)) # 打印类型
# 2. 解码:将字节转换回字符串,引入decode()函数,此函数接受一个bytes参数,返回一个字符串对象
a2 = a1.decode("utf-8") # 解码为 utf-8 字符串
print(a2) # 输出: 你好,世界
print(type(a2)) # 打印类型
# ============================================================
"""
2、字符串常用操作
字符运算符:
+:字符串链接
*:重复输出字符串
[]通过索引
"""
+51
View File
@@ -0,0 +1,51 @@
# README
回顾一下从头开始配置 Django 项目以展示你的 `zjptjg` 前端组件的主要步骤:
1. **项目结构确认**: 我们确认了你的项目结构,包含独立的 `backend` (Django) 和 `frontend` (HTML/CSS/JS) 目录。
2. **创建 Django 应用**: 你创建了名为 `zjptjg` 的 Django 应用 (`python manage.py startapp zjptjg`) 并将其添加到了 `settings.py` 的 `INSTALLED_APPS` 中。
3. **配置主 URL 路由**:
* 编辑了项目的主 `urls.py` 文件 (`backend/MDP/MDP/urls.py`)。
* 导入了 `include` 函数。
* 添加了 `path('zjptjg/', include('zjptjg.urls'))`,将所有访问 `/zjptjg/` 开头的请求转发给 `zjptjg` 应用处理。
4. **配置应用 URL 路由**:
* 在 `zjptjg` 应用目录下创建了 `urls.py` 文件。
* 在 `zjptjg/urls.py` 中定义了 `path('', views.index, name='zjptjg_index')`,将 `/zjptjg/` (即空路径,相对于应用根路径) 指向名为 `index` 的视图函数。
5. **创建视图函数**:
* 编辑了 `zjptjg/views.py` 文件。
* 创建了名为 `index` 的函数。
* 这个函数最终的作用是使用 `render(request, 'MDP/zjptjg/index.html')` 来渲染你的 HTML 文件。*(我们中间尝试过让它从数据库获取数据,但后来还原了)*
6. **配置模板目录**:
* 编辑了 `settings.py` 文件 (`backend/MDP/MDP/settings.py`)。
* 修改了 `TEMPLATES` 设置中的 `DIRS` 列表,加入了前端目录的路径 `[os.path.join(BASE_DIR.parent.parent, 'frontend')]`。这使得 Django 能够找到位于 `frontend` 目录下的 HTML 模板。
7. **配置静态文件目录**:
* 同样在 `settings.py` 文件中。
* 确认 `STATIC_URL = 'static/'`。
* 添加了 `STATICFILES_DIRS = [os.path.join(BASE_DIR.parent.parent, 'frontend')]`。这使得 Django 的开发服务器 (`runserver`) 能够找到位于 `frontend` 目录下的 CSS 和 JS 文件。
8. **修改 HTML 以使用静态文件标签**:
* 编辑了你的 `index.html` 文件 (`frontend/MDP/zjptjg/index.html`)。
* 在文件顶部添加了 `{% load static %}`。
* 将链接 CSS 的 `<link>` 标签的 `href` 修改为 `{% static 'MDP/zjptjg/style.css' %}`。
* 将引用 JS 的 `<script>` 标签的 `src` 修改为 `{% static 'MDP/zjptjg/script.js' %}`。
* 这利用了 Django 的静态文件处理机制来确保 CSS 和 JS 文件能被正确加载。
9. **(已还原) 模型和 Admin**:
* 我们曾尝试创建 `GeneralMachineSetting` 和 `StepSetting` 模型来匹配前端数据,并在 Admin 后台注册了它们。
* 之后根据你的要求,我们**撤销了**这些模型的创建、Admin 注册以及相关的数据库迁移操作。
10. **创建 Admin 超级用户**:
* 运行了 `python manage.py createsuperuser` 命令,设置了访问 `/admin` 后台所需的管理员账号和密码。
11. **运行和测试**:
* 使用 `python manage.py runserver` 启动了 Django 开发服务器。
* 通过访问 `http://127.0.0.1:8000/zjptjg/` 来查看页面效果。
* 通过访问 `http://127.0.0.1:8000/admin/` 来登录管理后台。
**总结:** 核心目标是让 Django 正确地找到并提供你的 HTML、CSS 和 JS 文件。关键配置在于 `settings.py` 中的 `TEMPLATES['DIRS']` 和 `STATICFILES_DIRS`,以及在 HTML 中使用 `{% static %}` 标签来引用静态资源。
@@ -0,0 +1,16 @@
"""
ASGI config for MDP project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MDP.settings')
application = get_asgi_application()
@@ -0,0 +1,130 @@
"""
Django settings for MDP project.
Generated by 'django-admin startproject' using Django 5.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""
from pathlib import Path
import os # 导入 os 模块
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-zu^ow%m3i!!&zcxnt&ixfpt*5z^wfh_9=urka+gju2r_xd(u*-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'zjptjg.apps.ZjptjgConfig'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MDP.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR.parent.parent, 'frontend')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MDP.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
STATIC_URL = 'static/'
# 添加额外的静态文件查找目录
STATICFILES_DIRS = [
os.path.join(BASE_DIR.parent.parent, 'frontend'),
]
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
@@ -0,0 +1,23 @@
"""
URL configuration for MDP project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('zjptjg/', include('zjptjg.urls')),
]
@@ -0,0 +1,16 @@
"""
WSGI config for MDP project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MDP.settings')
application = get_wsgi_application()
Binary file not shown.
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MDP.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ZjptjgConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "zjptjg"
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
@@ -0,0 +1,7 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='zjptjg_index'), # 访问 /zjptjg/ 时调用的视图
# 其他路由
]
@@ -0,0 +1,7 @@
from django.shortcuts import render
# Create your views here.
def index(request):
"""处理 /zjptjg/ 的请求,渲染前端页面"""
# 直接渲染静态模板,不传递额外上下文
return render(request, 'MDP/zjptjg/index.html')
@@ -0,0 +1,80 @@
{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>一般机构组件</title>
<link rel="stylesheet" href="{% static 'MDP/zjptjg/style.css' %}">
</head>
<body>
<!-- Main Component Display -->
<div id="machine-component" class="machine-component">
<div class="header">
<span id="machine-name-display">一般机构</span>
<div class="status-indicator"></div>
</div>
<div class="info-grid">
<div class="info-label">当前步骤</div>
<div id="current-step" class="info-value">第一步</div>
<div class="info-label">理论产能</div>
<div id="theoretical-ppm" class="info-value">60.00PPM</div>
<div class="info-label">当前产能</div>
<div id="current-ppm" class="info-value">59.05PPM</div>
</div>
<div id="machine-status" class="status-text">等待下料</div>
</div>
<!-- Settings Modal -->
<div id="settings-modal" class="modal-overlay" style="display: none;">
<div class="modal-content">
<!-- Fixed Header -->
<div class="modal-fixed-header">
<div class="modal-header">
<span id="modal-title">编辑-一般机构</span>
<button id="close-modal-btn" class="close-btn">&times;</button>
</div>
<div class="form-group">
<label for="machine-name-input">机构名称:</label>
<input type="text" id="machine-name-input" value="一般机构" required>
<span class="error-message" id="machine-name-error"></span>
</div>
<div class="form-group">
<label for="batch-quantity-input">批量处理数量:</label>
<input type="number" id="batch-quantity-input" value="1" min="0" step="1" placeholder="0代表禁用">
<span class="error-message" id="batch-quantity-error"></span>
</div>
<legend class="steps-legend">步骤设置:</legend>
</div>
<!-- Scrollable Steps Area -->
<div class="modal-scrollable-steps">
<div id="steps-container">
<!-- Steps will be added here by JS -->
</div>
</div>
<!-- Fixed Footer -->
<div class="modal-fixed-footer">
<button id="add-step-btn" class="add-btn">添加步骤</button>
<div class="form-group cache-group">
<input type="checkbox" id="has-cache-checkbox">
<label for="has-cache-checkbox">是否有缓存</label>
<input type="number" id="cache-quantity-input" min="1" step="1" placeholder="必须>0的整数" disabled>
<span class="error-message" id="cache-quantity-error"></span>
</div>
<div class="summary-section">
<span>总耗时: <span id="total-time-display">0.00</span>秒</span>
<span>理论产能: <span id="calculated-ppm-display">0.00</span>PPM</span>
</div>
<div class="modal-footer">
<button id="save-settings-btn" class="save-btn">保存</button>
<button id="cancel-settings-btn" class="cancel-btn">取消</button>
</div>
</div>
</div>
</div>
<script src="{% static 'MDP/zjptjg/script.js' %}"></script>
</body>
</html>
@@ -0,0 +1,436 @@
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const machineComponent = document.getElementById('machine-component');
const settingsModal = document.getElementById('settings-modal');
const closeModalBtn = document.getElementById('close-modal-btn');
const cancelSettingsBtn = document.getElementById('cancel-settings-btn');
const saveSettingsBtn = document.getElementById('save-settings-btn');
const addStepBtn = document.getElementById('add-step-btn');
const stepsContainer = document.getElementById('steps-container');
const machineNameInput = document.getElementById('machine-name-input');
const batchQuantityInput = document.getElementById('batch-quantity-input');
const hasCacheCheckbox = document.getElementById('has-cache-checkbox');
const cacheQuantityInput = document.getElementById('cache-quantity-input');
const totalTimeDisplay = document.getElementById('total-time-display');
const calculatedPpmDisplay = document.getElementById('calculated-ppm-display');
const machineNameDisplay = document.getElementById('machine-name-display');
const theoreticalPpmDisplay = document.getElementById('theoretical-ppm');
const modalTitle = document.getElementById('modal-title');
const statusIndicator = machineComponent.querySelector('.status-indicator');
const machineStatus = document.getElementById('machine-status');
// --- State ---
let steps = []; // Array to hold step data
let initialSettings = {}; // 恢复为空对象
let isActive = false; // 恢复状态变量
let isDisabled = false;
// --- Functions ---
const updateMachineStatus = (newStatusText) => {
machineStatus.textContent = newStatusText;
statusIndicator.classList.remove('active', 'disabled'); // 清除状态
isDisabled = false;
isActive = false;
if (newStatusText === '运行中') {
statusIndicator.classList.add('active');
isActive = true;
} else if (newStatusText === '禁用中') {
statusIndicator.classList.add('disabled');
isDisabled = true;
} else {
// 默认黄色脉冲,不需要特定类
}
// 恢复存储状态逻辑
if (initialSettings) {
initialSettings.statusText = newStatusText;
initialSettings.isActive = isActive;
initialSettings.isDisabled = isDisabled;
}
};
// --- Validation Helpers ---
const clearValidationErrors = () => {
const errorMessages = settingsModal.querySelectorAll('.error-message');
errorMessages.forEach(msg => {
msg.textContent = '';
msg.style.display = 'none';
});
const invalidInputs = settingsModal.querySelectorAll('.invalid');
invalidInputs.forEach(input => input.classList.remove('invalid'));
};
const showValidationError = (inputElement, message) => {
inputElement.classList.add('invalid');
const errorSpanId = inputElement.id + '-error'; // Assumes error span ID convention
const errorSpan = document.getElementById(errorSpanId);
if (errorSpan) {
errorSpan.textContent = message;
errorSpan.style.display = 'block';
}
// Focus the first invalid element found
if (!settingsModal.querySelector('.invalid:focus')) {
inputElement.focus();
}
};
// Function to remove error state when user types
const clearErrorOnInput = (event) => {
const inputElement = event.target;
inputElement.classList.remove('invalid');
const errorSpanId = inputElement.id + '-error';
const errorSpan = document.getElementById(errorSpanId);
if (errorSpan) {
errorSpan.textContent = '';
errorSpan.style.display = 'none';
}
};
// --- Main Validation Logic ---
const validateSettings = () => {
clearValidationErrors();
let isValid = true;
const errors = [];
// 1. Check Machine Name
if (!machineNameInput.value.trim()) {
showValidationError(machineNameInput, '机构名称不能为空');
isValid = false;
errors.push('机构名称不能为空');
}
// 2. Check Batch Quantity
const batchQuantityValue = batchQuantityInput.value;
if (batchQuantityValue === '' || !Number.isInteger(Number(batchQuantityValue)) || Number(batchQuantityValue) < 0) {
showValidationError(batchQuantityInput, '批量处理数量必须是非负整数');
isValid = false;
errors.push('批量处理数量必须是非负整数');
}
// 3. Check Steps
steps.forEach((step, index) => {
const stepIndexDisplay = index + 1;
// Check Step Name
if (!step.nameInput.value.trim()) {
showValidationError(step.nameInput, `步骤 ${stepIndexDisplay} 名称不能为空`);
isValid = false;
errors.push(`步骤 ${stepIndexDisplay} 名称不能为空`);
}
// Add listeners to step inputs dynamically if not already added
if (!step.nameInput.dataset.listenerAdded) {
step.nameInput.addEventListener('input', clearErrorOnInput);
step.nameInput.dataset.listenerAdded = 'true';
}
// Note: We are not validating start/work time based on requirements, only name
});
// 4. Check Cache Quantity (if applicable)
if (hasCacheCheckbox.checked) {
const cacheQuantityValue = cacheQuantityInput.value;
if (cacheQuantityValue === '' || !Number.isInteger(Number(cacheQuantityValue)) || Number(cacheQuantityValue) <= 0) {
showValidationError(cacheQuantityInput, '缓存数量必须是大于0的整数');
isValid = false;
errors.push('缓存数量必须是大于0的整数');
}
}
if (!isValid) {
// Optionally display a summary alert, though inline errors are better UX
// alert('请修正以下错误:\n- ' + errors.join('\n- '));
}
return isValid;
};
// Calculate Total Time and Theoretical PPM
const calculateMetrics = () => {
let totalDuration = 0;
let maxEndTime = 0;
steps.forEach(step => {
const startTime = parseFloat(step.startTimeInput.value) || 0;
const workTime = parseFloat(step.workTimeInput.value) || 0;
const endTime = startTime + workTime;
if (endTime > maxEndTime) {
maxEndTime = endTime;
}
});
totalDuration = maxEndTime;
totalTimeDisplay.textContent = totalDuration.toFixed(2);
const batchQuantityRaw = batchQuantityInput.value;
let batchQuantity = 1; // Default if invalid for calculation display
// Use valid integer for calculation, default to 1 if invalid or 0
if (batchQuantityRaw !== '' && Number.isInteger(Number(batchQuantityRaw)) && Number(batchQuantityRaw) > 0) {
batchQuantity = parseInt(batchQuantityRaw);
}
let calculatedPpm = 0;
if (totalDuration > 0) {
calculatedPpm = (60 / totalDuration) * batchQuantity;
}
calculatedPpmDisplay.textContent = calculatedPpm.toFixed(2);
};
// Update Step Titles (e.g., "步骤 1", "步骤 2")
const updateStepTitles = () => {
steps.forEach((step, index) => {
step.element.querySelector('.step-title').textContent = `步骤 ${index + 1}`;
step.element.dataset.index = index; // Update data-index for reordering
});
calculateMetrics(); // Recalculate when steps change order/number
};
// Create HTML for a single step
const createStepElement = (stepData = {}, index) => {
const stepId = `step-${Date.now()}-${Math.random()}`;
const stepDiv = document.createElement('div');
stepDiv.classList.add('step-item');
stepDiv.id = stepId;
stepDiv.dataset.index = index;
stepDiv.innerHTML = `
<div class="step-header">
<span class="step-title">步骤 ${index + 1}</span>
<div class="step-controls">
<button class="step-btn move-up-btn" title="上移">&#x2191;</button>
<button class="step-btn move-down-btn" title="下移">&#x2193;</button>
<button class="step-btn delete-step-btn" title="删除">&#x2716;</button>
</div>
</div>
<div class="step-inputs">
<div class="form-group">
<label for="step-name-${stepId}">名称:</label>
<input type="text" id="step-name-${stepId}" class="step-name-input" value="${stepData.name || `步骤${index + 1}`}" maxlength="12" required>
<span class="error-message step-error" id="step-name-error-${stepId}"></span>
</div>
<div class="form-group">
<label for="step-start-${stepId}">开始时间(秒):</label>
<input type="number" id="step-start-${stepId}" class="step-start-input" value="${stepData.startTime || 0}" min="0" step="0.1">
<span class="error-message step-error" id="step-start-error-${stepId}"></span>
</div>
<div class="form-group">
<label for="step-work-${stepId}">工作时间(秒):</label>
<input type="number" id="step-work-${stepId}" class="step-work-input" value="${stepData.workTime || 0}" min="0" step="0.1">
<span class="error-message step-error" id="step-work-error-${stepId}"></span>
</div>
</div>
`;
// Add event listeners for controls within this step
stepDiv.querySelector('.delete-step-btn').addEventListener('click', () => deleteStep(stepId));
stepDiv.querySelector('.move-up-btn').addEventListener('click', () => moveStep(stepId, -1));
stepDiv.querySelector('.move-down-btn').addEventListener('click', () => moveStep(stepId, 1));
// Add listeners to inputs for real-time calculation and error clearing
const nameInput = stepDiv.querySelector('.step-name-input');
const startTimeInput = stepDiv.querySelector('.step-start-input');
const workTimeInput = stepDiv.querySelector('.step-work-input');
[startTimeInput, workTimeInput, batchQuantityInput].forEach(input => {
input.addEventListener('input', calculateMetrics);
});
// Add input listener for validation clearing (only needed once per element)
if (!nameInput.dataset.listenerAdded) {
nameInput.addEventListener('input', clearErrorOnInput);
nameInput.dataset.listenerAdded = 'true';
}
return { element: stepDiv, id: stepId, nameInput, startTimeInput, workTimeInput };
};
// Add a new step
const addStep = (stepData = {}) => {
const newIndex = steps.length;
const newStep = createStepElement(stepData, newIndex);
stepsContainer.appendChild(newStep.element);
steps.push(newStep);
updateStepTitles();
};
// Delete a step
const deleteStep = (stepId) => {
const stepIndex = steps.findIndex(s => s.id === stepId);
if (stepIndex > -1) {
steps[stepIndex].element.remove();
steps.splice(stepIndex, 1);
updateStepTitles();
}
};
// Move a step up or down
const moveStep = (stepId, direction) => {
const index = steps.findIndex(s => s.id === stepId);
const newIndex = index + direction;
if (newIndex >= 0 && newIndex < steps.length) {
// Visual feedback
const currentElement = steps[index].element;
currentElement.classList.add('moving');
setTimeout(() => {
currentElement.classList.remove('moving');
// Also remove from the swapped element if it had the class briefly
if (steps[newIndex] && steps[newIndex].element) {
steps[newIndex].element.classList.remove('moving');
}
}, 300); // Match CSS transition duration
// Swap in the steps array
[steps[index], steps[newIndex]] = [steps[newIndex], steps[index]];
// Re-insert elements in the DOM based on the new order
stepsContainer.innerHTML = ''; // Clear container
steps.forEach(step => stepsContainer.appendChild(step.element)); // Re-append in new order
updateStepTitles();
}
};
// Toggle Cache Quantity Input
const toggleCacheInput = () => {
const isChecked = hasCacheCheckbox.checked;
cacheQuantityInput.disabled = !isChecked;
if (isChecked) {
cacheQuantityInput.required = true; // Make required when checked
} else {
cacheQuantityInput.required = false; // Not required when unchecked
cacheQuantityInput.value = ''; // Clear value when disabled
// Clear potential validation error when disabling
cacheQuantityInput.classList.remove('invalid');
const errorSpan = document.getElementById('cache-quantity-input-error');
if (errorSpan) {
errorSpan.textContent = '';
errorSpan.style.display = 'none';
}
}
};
// Open Settings Modal
const openModal = () => {
clearValidationErrors();
// 恢复为从当前状态存储设置
initialSettings = {
name: machineNameInput.value,
batchQuantity: batchQuantityInput.value,
hasCache: hasCacheCheckbox.checked,
cacheQuantity: cacheQuantityInput.value,
stepsData: steps.map(s => ({
name: s.nameInput.value,
startTime: s.startTimeInput.value,
workTime: s.workTimeInput.value
})),
isActive: statusIndicator.classList.contains('active'),
isDisabled: statusIndicator.classList.contains('disabled'),
statusText: machineStatus.textContent,
theoreticalPPM: theoreticalPpmDisplay.textContent,
currentStep: document.getElementById('current-step').textContent,
currentPPM: document.getElementById('current-ppm').textContent
};
// 恢复从JS状态重建模态框步骤
stepsContainer.innerHTML = '';
steps = [];
initialSettings.stepsData.forEach(stepData => addStep(stepData));
modalTitle.textContent = `编辑-${initialSettings.name || '一般机构'}`;
toggleCacheInput();
calculateMetrics();
settingsModal.style.display = 'flex';
};
// Close Settings Modal
const closeModal = () => {
settingsModal.style.display = 'none';
};
// Revert settings to initial state (on cancel or 'X' click)
const revertSettings = () => {
clearValidationErrors();
machineNameInput.value = initialSettings.name;
batchQuantityInput.value = initialSettings.batchQuantity;
hasCacheCheckbox.checked = initialSettings.hasCache;
cacheQuantityInput.value = initialSettings.cacheQuantity;
toggleCacheInput();
stepsContainer.innerHTML = '';
steps = [];
initialSettings.stepsData.forEach(stepData => addStep(stepData));
// 恢复主显示状态
machineNameDisplay.textContent = initialSettings.name;
theoreticalPpmDisplay.textContent = initialSettings.theoreticalPPM;
updateMachineStatus(initialSettings.statusText);
document.getElementById('current-step').textContent = initialSettings.currentStep;
document.getElementById('current-ppm').textContent = initialSettings.currentPPM;
closeModal();
};
// Save Settings
const saveSettings = () => {
if (!validateSettings()) {
console.log("Validation failed.");
return;
}
console.log("Validation passed.");
const newName = machineNameInput.value.trim();
const batchQty = parseInt(batchQuantityInput.value);
machineNameDisplay.textContent = newName;
calculateMetrics();
theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM';
if (batchQty === 0) {
updateMachineStatus('禁用中');
} else {
updateMachineStatus('运行中');
}
document.getElementById('current-step').textContent = steps.length > 0 ? steps[0].nameInput.value : '无步骤';
document.getElementById('current-ppm').textContent = '0.00PPM';
closeModal();
};
// --- Event Listeners ---
machineComponent.addEventListener('dblclick', openModal);
closeModalBtn.addEventListener('click', revertSettings);
cancelSettingsBtn.addEventListener('click', revertSettings);
saveSettingsBtn.addEventListener('click', saveSettings);
addStepBtn.addEventListener('click', () => addStep());
hasCacheCheckbox.addEventListener('change', toggleCacheInput);
machineNameInput.addEventListener('input', clearErrorOnInput);
batchQuantityInput.addEventListener('input', clearErrorOnInput);
cacheQuantityInput.addEventListener('input', clearErrorOnInput);
// --- Initialization ---
const initialize = () => {
// 恢复添加默认步骤
addStep({ name: '步骤1', startTime: 0, workTime: 3 });
addStep({ name: '步骤2', startTime: 2, workTime: 3 });
// 恢复设置默认值
machineNameInput.value = '一般机构';
batchQuantityInput.value = 1;
hasCacheCheckbox.checked = true;
cacheQuantityInput.value = 3;
toggleCacheInput();
machineNameDisplay.textContent = machineNameInput.value;
calculateMetrics();
theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM';
document.getElementById('current-step').textContent = '步骤1';
document.getElementById('current-ppm').textContent = '0.00PPM';
updateMachineStatus('等待中');
// 恢复存储初始理论PPM
if (!initialSettings.theoreticalPPM) {
initialSettings.theoreticalPPM = theoreticalPpmDisplay.textContent;
}
clearValidationErrors();
};
initialize();
});
@@ -0,0 +1,679 @@
/* 全局和页面基础样式 */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f6; /* 页面背景色 */
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
min-height: 100vh;
margin: 0;
}
/* --- 主组件显示区域样式 --- */
.machine-component {
background-color: #ffffff; /* 组件背景色 */
border-radius: 12px; /* 圆角 */
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 阴影 */
padding: 15px; /* Adjusted padding */
max-width: 350px; /* Max width on larger screens */
width: 90%; /* Relative width on smaller screens */
margin: 10px; /* Add some margin */
cursor: pointer; /* 鼠标样式 */
transition: box-shadow 0.3s ease; /* 阴影过渡效果 */
border: 1px solid #e0e0e0; /* 边框 */
}
.machine-component:hover {
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); /* 鼠标悬浮时阴影加强 */
}
/* 主组件头部 */
.header {
display: flex;
justify-content: space-between; /* 两端对齐 */
align-items: center; /* 垂直居中 */
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid #eee; /* 底部边框分割线 */
}
/* 主组件 - 机构名称 */
#machine-name-display {
font-size: 1.2em;
font-weight: 600;
color: #333;
}
/* 主组件 - 状态指示灯 */
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%; /* 圆形 */
background-color: #ffc107; /* Default Yellow for waiting */
transition: background-color 0.3s ease; /* Keep transition for color change */
/* Apply default yellow pulse animation */
animation: pulse-yellow 1.5s infinite;
}
/* Active state overrides */
.status-indicator.active {
background-color: #4CAF50; /* Green when active */
animation-name: pulse-green; /* Change animation name */
}
/* Disabled state overrides */
.status-indicator.disabled {
background-color: #dc3545; /* Red when disabled */
animation-name: pulse-red; /* Use red pulse */
}
/* Define the GREEN pulse animation */
@keyframes pulse-green {
0% {
box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.5); /* Green shadow */
}
70% {
box-shadow: 0 0 0 8px rgba(76, 175, 80, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(76, 175, 80, 0);
}
}
/* Define the YELLOW pulse animation */
@keyframes pulse-yellow {
0% {
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.5); /* Yellow shadow */
}
70% {
box-shadow: 0 0 0 8px rgba(255, 193, 7, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
}
}
/* Define the RED pulse animation */
@keyframes pulse-red {
0% {
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.5); /* Red shadow */
}
70% {
box-shadow: 0 0 0 8px rgba(220, 53, 69, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0);
}
}
/* 主组件 - 信息网格布局 */
.info-grid {
display: grid;
grid-template-columns: auto 1fr; /* 标签自适应,值占满剩余空间 */
gap: 8px 15px; /* 行间距 列间距 */
margin-bottom: 15px;
font-size: 0.95em;
}
/* 主组件 - 信息标签 */
.info-label {
color: #555;
font-weight: 500;
text-align: right; /* 文本右对齐 */
}
/* 主组件 - 信息值 */
.info-value {
color: #333;
font-weight: 600;
}
/* 主组件 - 底部状态文本 */
.status-text {
text-align: center;
font-weight: 500;
color: #666;
padding-top: 10px;
border-top: 1px solid #eee; /* 顶部边框分割线 */
font-size: 0.9em;
}
/* --- 设置弹窗 (Modal) 样式 --- */
/* 弹窗遮罩层 */
.modal-overlay {
position: fixed; /* 固定定位,覆盖全屏 */
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
display: flex;
justify-content: center; /* 水平居中弹窗内容 */
align-items: center; /* 垂直居中弹窗内容 */
z-index: 1000; /* 置于顶层 */
}
/* 弹窗内容区域 */
.modal-content {
background-color: #fff;
border-radius: 10px; /* 圆角 */
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
max-width: 600px; /* Max width on larger screens */
width: 90vw; /* Relative width */
max-height: 90vh; /* 最大高度为视窗的90% */
display: flex; /* Use flexbox for layout */
flex-direction: column; /* Stack header, scroll, footer vertically */
overflow: hidden; /* Re-add overflow hidden to clip children and enforce height */
}
/* Remove scrollbar styles from .modal-content */
/*
.modal-content::-webkit-scrollbar { ... }
.modal-content::-webkit-scrollbar-track { ... }
.modal-content::-webkit-scrollbar-thumb { ... }
.modal-content::-webkit-scrollbar-thumb:hover { ... }
*/
/* Fixed Header Section */
.modal-fixed-header {
padding: 20px 25px 0 25px; /* Padding T, R/L, B */
border-bottom: 1px solid #eee; /* Separator */
}
.steps-legend {
/* Styles for the moved legend */
font-weight: 600;
color: #333;
padding: 10px 0 5px 0; /* Adjust padding */
margin: 0; /* Remove default legend margin */
font-size: 1.1em; /* Match step-title size */
}
/* Scrollable Steps Area */
.modal-scrollable-steps {
flex-grow: 1; /* Allow this section to take available vertical space */
overflow-y: auto; /* Enable vertical scrolling ONLY for this section */
padding: 15px 25px; /* Padding inside the scrollable area */
/* Apply custom scrollbar styles HERE */
scrollbar-width: thin; /* Firefox */
scrollbar-color: #ccc #f4f4f4; /* Firefox */
}
.modal-scrollable-steps::-webkit-scrollbar {
width: 8px;
}
.modal-scrollable-steps::-webkit-scrollbar-track {
background: #f4f4f4;
border-radius: 10px;
margin: 5px 0; /* Add slight margin */
}
.modal-scrollable-steps::-webkit-scrollbar-thumb {
background-color: #ccc;
border-radius: 10px;
border: 2px solid #f4f4f4;
}
.modal-scrollable-steps::-webkit-scrollbar-thumb:hover {
background-color: #aaa;
}
/* Fixed Footer Section */
.modal-fixed-footer {
padding: 10px 25px 20px 25px; /* Padding T, R/L, B */
border-top: 1px solid #eee; /* Separator */
background-color: #fff; /* Ensure solid background */
}
/* Adjustments for items moved to footer */
.modal-fixed-footer .add-btn {
margin-top: 10px; /* Adjust top margin */
margin-bottom: 15px; /* Add bottom margin */
}
.modal-fixed-footer .cache-group {
margin-bottom: 15px; /* Add consistent margin */
}
.modal-fixed-footer .summary-section {
margin-top: 15px; /* Adjust top margin */
padding-top: 0; /* Remove padding as border is above */
border-top: none; /* Remove border as it's on footer now */
}
.modal-fixed-footer .modal-footer {
margin-top: 15px; /* Adjust top margin */
padding-top: 0; /* Remove padding as border is above */
border-top: none; /* Remove border as it's on footer now */
}
/* Remove original steps-config styling */
/*
.steps-config { ... }
.steps-config legend { ... }
*/
/* 弹窗头部 */
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
margin-bottom: 20px;
}
/* 弹窗标题 */
#modal-title {
font-size: 1.4em;
font-weight: 600;
color: #333;
}
/* 弹窗关闭按钮 */
.close-btn {
background: none;
border: none;
font-size: 1.8em;
cursor: pointer;
color: #888;
}
.close-btn:hover {
color: #333;
}
/* 弹窗主体内容区域 */
.modal-body {
margin-bottom: 20px;
}
/* 通用表单组样式 */
.form-group {
margin-bottom: 15px;
display: grid;
grid-template-columns: 120px 1fr; /* 标签固定宽度,输入框占满剩余 - Default */
align-items: center;
gap: 5px 10px; /* Reduced gap slightly */
}
/* 表单标签 */
.form-group label {
font-weight: 500;
color: #555;
text-align: right;
}
/* 表单输入框 (文本和数字) */
.form-group input[type="text"],
.form-group input[type="number"] {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 0.95em;
transition: border-color 0.3s ease;
}
/* 输入框获取焦点时样式 */
.form-group input[type="text"]:focus,
.form-group input[type="number"]:focus {
border-color: #007bff; /* 边框变蓝 */
outline: none; /* 移除默认轮廓 */
}
/* 禁用的数字输入框 */
.form-group input[type="number"][disabled] {
background-color: #e9ecef;
cursor: not-allowed;
}
/* --- 步骤设置区域 --- */
.steps-config {
border: 1px solid #ddd; /* 边框 */
border-radius: 8px; /* 圆角 */
padding: 15px;
margin-bottom: 20px;
}
/* 步骤设置区域标题 */
.steps-config legend {
font-weight: 600;
color: #333;
padding: 0 10px;
}
/* 单个步骤项 */
.step-item {
border: 1px dashed #ccc; /* 虚线边框 */
border-radius: 6px;
padding: 15px;
margin-bottom: 15px;
position: relative;
background-color: #f9f9f9;
}
/* 步骤项头部 */
.step-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
/* 步骤标题 (如: 步骤 1) */
.step-title {
font-weight: bold;
font-size: 1.1em;
}
/* 步骤控制按钮组 (上移/下移/删除) */
.step-controls {
display: flex;
gap: 5px;
}
/* 步骤控制按钮通用样式 */
.step-btn {
background: none;
border: none;
cursor: pointer;
font-size: 1.2em;
color: #888;
}
.step-btn:hover { color: #333; }
/* 删除按钮特定颜色 */
.delete-step-btn { color: #dc3545; }
.delete-step-btn:hover { color: #a71d2a; }
/* 步骤内部输入框布局 */
.step-inputs {
display: grid;
grid-template-columns: auto 1fr 1fr; /* 名称自适应,时间占剩余空间 - Default */
gap: 10px;
align-items: start; /* 顶部对齐 */
}
/* 步骤内表单组 */
.step-inputs .form-group {
grid-template-columns: 1fr; /* 内部标签和输入框垂直排列 */
margin-bottom: 0;
gap: 3px;
}
/* 步骤内标签样式 */
.step-inputs label {
text-align: left;
font-size: 0.85em;
margin-bottom: 2px;
color: #666;
display: block; /* 确保独占一行 */
white-space: nowrap; /* 防止标签换行 */
overflow: hidden; /* 隐藏超出部分 */
text-overflow: ellipsis; /* 超出部分显示省略号 */
max-width: 100%; /* 防止标签撑开布局 */
}
/* 限制步骤内时间输入框的最大宽度 */
.step-inputs .form-group:nth-child(2) input[type="number"],
.step-inputs .form-group:nth-child(3) input[type="number"] {
max-width: 85px; /* 最大宽度限制 */
width: 100%; /* 允许在容器缩小时也缩小 */
}
/* 确保步骤内名称输入框填满其列 */
.step-inputs .form-group:nth-child(1) input[type="text"] {
width: 85%;
}
/* --- 其他设置和按钮 --- */
/* 添加步骤按钮 */
.add-btn {
padding: 8px 15px;
background-color: #28a745;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 0.95em;
transition: background-color 0.3s ease;
margin-top: 15px;
/* 居中显示 */
display: block;
width: fit-content; /* 宽度自适应内容 */
margin-left: auto;
margin-right: auto;
}
.add-btn:hover {
background-color: #218838;
}
/* 缓存设置组 */
.cache-group {
display: grid; /* Use grid for better control with errors */
grid-template-columns: auto auto 1fr; /* checkbox, label, input - Default */
align-items: center;
gap: 10px;
}
/* 缓存复选框 */
.cache-group input[type="checkbox"] { grid-row: 1; }
.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; }
.cache-group input[type="number"] { grid-row: 1; }
.cache-group .error-message {
grid-column: 3; /* Error below the number input */
grid-row: 2;
margin-top: 2px;
}
/* 汇总信息区域 */
.summary-section {
margin-top: 20px;
padding-top: 15px;
border-top: 1px solid #eee;
display: flex;
justify-content: space-around; /* 两端分散对齐 */
font-size: 0.95em;
color: #555;
}
/* 汇总信息中的数值 */
.summary-section span span {
font-weight: 600;
color: #333;
}
/* 弹窗底部按钮区域 */
.modal-footer {
display: flex;
justify-content: flex-end; /* 按钮靠右对齐 */
gap: 10px;
padding-top: 15px;
border-top: 1px solid #eee;
margin-top: 20px;
}
/* 保存和取消按钮通用样式 */
.save-btn,
.cancel-btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s ease, color 0.3s ease;
}
/* 保存按钮 */
.save-btn {
background-color: #007bff;
color: white;
}
.save-btn:hover {
background-color: #0056b3;
}
/* 取消按钮 */
.cancel-btn {
background-color: #f8f9fa;
color: #333;
border: 1px solid #ccc;
}
.cancel-btn:hover {
background-color: #e2e6ea;
}
/* --- 工具类样式 --- */
/* 错误消息 (未使用,可备用) */
.error-message {
color: #dc3545;
font-size: 0.85em; /* Slightly larger */
padding-left: 0; /* Remove padding */
display: none; /* Hidden by default */
margin-top: 2px; /* Add small top margin */
}
/* Ensure error message appears below input in standard form groups */
.form-group .error-message {
grid-column: 2; /* Align with input */
grid-row: 2; /* Place on the row below the input */
text-align: left;
}
/* Error messages within steps */
.step-inputs .error-message {
/* display: block; */ /* Already block by default */
width: 100%; /* Take full width */
margin-top: 2px;
text-align: left;
}
/* Adjust cache group alignment when error shows */
.cache-group {
display: grid; /* Use grid for better control with errors */
grid-template-columns: auto auto 1fr; /* checkbox, label, input */
align-items: center;
gap: 10px;
}
.cache-group input[type="checkbox"] { grid-row: 1; }
.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; }
.cache-group input[type="number"] { grid-row: 1; }
.cache-group .error-message {
grid-column: 3; /* Error below the number input */
grid-row: 2;
margin-top: 2px;
}
/* 步骤项移动时的视觉反馈 */
.step-item.moving {
transition: background-color 0.3s ease-out;
background-color: #e6f7ff; /* 淡蓝色高亮 */
}
/* Input Validation Styles */
input:invalid,
textarea:invalid {
border-color: #dc3545; /* Red border for invalid fields */
}
.form-group input.invalid,
.step-item input.invalid {
border-color: #dc3545 !important; /* Force red border */
background-color: #fff3f3; /* Light red background */
}
.error-tooltip {
color: #dc3545;
font-size: 0.8em;
padding-left: 5px;
display: none; /* Hidden by default */
}
.form-group .error-tooltip {
grid-column: 2; /* Align with input in main form groups */
}
/* --- Responsive Adjustments --- */
@media (max-width: 600px) {
/* Reduce padding/font size slightly globally in modal? Optional */
.modal-content {
width: 95vw; /* Use more width on mobile */
max-height: 95vh; /* Allow slightly more height */
}
.modal-fixed-header,
.modal-scrollable-steps,
.modal-fixed-footer {
padding: 15px; /* Consistent padding */
}
/* Stack form groups vertically */
.form-group {
grid-template-columns: 1fr; /* Single column */
gap: 5px; /* Reduce gap */
}
.form-group label {
text-align: left; /* Align labels left */
margin-bottom: 2px;
}
/* Ensure error messages span full width below input */
.form-group .error-message {
grid-column: 1; /* Span full column */
grid-row: 3; /* Ensure it's below label and input */
}
/* Stack step inputs vertically */
.step-inputs {
grid-template-columns: 1fr; /* Single column */
gap: 10px;
}
/* Allow time inputs to take more width when stacked */
.step-inputs .form-group:nth-child(2) input[type="number"],
.step-inputs .form-group:nth-child(3) input[type="number"] {
max-width: none; /* Remove max-width limit */
}
/* Stack cache group elements */
.cache-group {
grid-template-columns: auto 1fr; /* Checkbox | Label & Input */
gap: 5px 10px;
}
.cache-group input[type="checkbox"] { grid-row: 1; grid-column: 1; }
.cache-group label[for="has-cache-checkbox"] { grid-row: 1; grid-column: 2; }
.cache-group input[type="number"] { grid-row: 2; grid-column: 1 / span 2; width: 100%;} /* Input below */
.cache-group .error-message {
grid-row: 3; /* Error below input */
grid-column: 1 / span 2;
}
/* Stack summary section */
.summary-section {
flex-direction: column; /* Stack items */
align-items: center; /* Center align */
gap: 5px;
}
/* Adjust footer buttons */
.modal-footer {
justify-content: space-around; /* Space out buttons more */
}
.save-btn,
.cancel-btn {
padding: 8px 15px; /* Slightly smaller buttons */
font-size: 0.95em;
}
}
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>一般机构组件</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Main Component Display -->
<div id="machine-component" class="machine-component">
<div class="header">
<span id="machine-name-display">一般机构</span>
<div class="status-indicator"></div>
</div>
<div class="info-grid">
<div class="info-label">当前步骤</div>
<div id="current-step" class="info-value">第一步</div>
<div class="info-label">理论产能</div>
<div id="theoretical-ppm" class="info-value">60.00PPM</div>
<div class="info-label">当前产能</div>
<div id="current-ppm" class="info-value">59.05PPM</div>
</div>
<div id="machine-status" class="status-text">等待下料</div>
</div>
<!-- Settings Modal -->
<div id="settings-modal" class="modal-overlay" style="display: none;">
<div class="modal-content">
<!-- Fixed Header -->
<div class="modal-fixed-header">
<div class="modal-header">
<span id="modal-title">编辑-一般机构</span>
<button id="close-modal-btn" class="close-btn">&times;</button>
</div>
<div class="form-group">
<label for="machine-name-input">机构名称:</label>
<input type="text" id="machine-name-input" value="一般机构" required>
<span class="error-message" id="machine-name-error"></span>
</div>
<div class="form-group">
<label for="batch-quantity-input">批量处理数量:</label>
<input type="number" id="batch-quantity-input" value="1" min="0" step="1" placeholder="0代表禁用">
<span class="error-message" id="batch-quantity-error"></span>
</div>
<legend class="steps-legend">步骤设置:</legend>
</div>
<!-- Scrollable Steps Area -->
<div class="modal-scrollable-steps">
<div id="steps-container">
<!-- Steps will be added here by JS -->
</div>
</div>
<!-- Fixed Footer -->
<div class="modal-fixed-footer">
<button id="add-step-btn" class="add-btn">添加步骤</button>
<div class="form-group cache-group">
<input type="checkbox" id="has-cache-checkbox">
<label for="has-cache-checkbox">是否有缓存</label>
<input type="number" id="cache-quantity-input" min="1" step="1" placeholder="必须>0的整数" disabled>
<span class="error-message" id="cache-quantity-error"></span>
</div>
<div class="summary-section">
<span>总耗时: <span id="total-time-display">0.00</span>秒</span>
<span>理论产能: <span id="calculated-ppm-display">0.00</span>PPM</span>
</div>
<div class="modal-footer">
<button id="save-settings-btn" class="save-btn">保存</button>
<button id="cancel-settings-btn" class="cancel-btn">取消</button>
</div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
@@ -0,0 +1,452 @@
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const machineComponent = document.getElementById('machine-component');
const settingsModal = document.getElementById('settings-modal');
const closeModalBtn = document.getElementById('close-modal-btn');
const cancelSettingsBtn = document.getElementById('cancel-settings-btn');
const saveSettingsBtn = document.getElementById('save-settings-btn');
const addStepBtn = document.getElementById('add-step-btn');
const stepsContainer = document.getElementById('steps-container');
const machineNameInput = document.getElementById('machine-name-input');
const batchQuantityInput = document.getElementById('batch-quantity-input');
const hasCacheCheckbox = document.getElementById('has-cache-checkbox');
const cacheQuantityInput = document.getElementById('cache-quantity-input');
const totalTimeDisplay = document.getElementById('total-time-display');
const calculatedPpmDisplay = document.getElementById('calculated-ppm-display');
const machineNameDisplay = document.getElementById('machine-name-display');
const theoreticalPpmDisplay = document.getElementById('theoretical-ppm');
const modalTitle = document.getElementById('modal-title');
const statusIndicator = machineComponent.querySelector('.status-indicator'); // Get status indicator
const machineStatus = document.getElementById('machine-status'); // Get status text element
// --- State ---
let steps = []; // Array to hold step data
let initialSettings = {}; // To store settings when modal opens
let isActive = false; // Track if the machine is considered active
let isDisabled = false; // Track if machine is disabled (batch=0)
// --- Functions ---
// Helper function to update status text AND indicator light
const updateMachineStatus = (newStatusText) => {
machineStatus.textContent = newStatusText;
statusIndicator.classList.remove('active', 'disabled'); // Clear previous state classes
isDisabled = false;
isActive = false;
if (newStatusText === '运行中') {
statusIndicator.classList.add('active');
isActive = true;
} else if (newStatusText === '禁用中') {
statusIndicator.classList.add('disabled');
isDisabled = true;
} else {
// Default: Waiting (yellow pulse) - no specific class needed
}
// Store the current text and state in case modal is opened later
if (initialSettings) { // Prevent error during initial load
initialSettings.statusText = newStatusText;
initialSettings.isActive = isActive;
initialSettings.isDisabled = isDisabled;
}
};
// --- Validation Helpers ---
const clearValidationErrors = () => {
const errorMessages = settingsModal.querySelectorAll('.error-message');
errorMessages.forEach(msg => {
msg.textContent = '';
msg.style.display = 'none';
});
const invalidInputs = settingsModal.querySelectorAll('.invalid');
invalidInputs.forEach(input => input.classList.remove('invalid'));
};
const showValidationError = (inputElement, message) => {
inputElement.classList.add('invalid');
const errorSpanId = inputElement.id + '-error'; // Assumes error span ID convention
const errorSpan = document.getElementById(errorSpanId);
if (errorSpan) {
errorSpan.textContent = message;
errorSpan.style.display = 'block';
}
// Focus the first invalid element found
if (!settingsModal.querySelector('.invalid:focus')) {
inputElement.focus();
}
};
// Function to remove error state when user types
const clearErrorOnInput = (event) => {
const inputElement = event.target;
inputElement.classList.remove('invalid');
const errorSpanId = inputElement.id + '-error';
const errorSpan = document.getElementById(errorSpanId);
if (errorSpan) {
errorSpan.textContent = '';
errorSpan.style.display = 'none';
}
};
// --- Main Validation Logic ---
const validateSettings = () => {
clearValidationErrors();
let isValid = true;
const errors = [];
// 1. Check Machine Name
if (!machineNameInput.value.trim()) {
showValidationError(machineNameInput, '机构名称不能为空');
isValid = false;
errors.push('机构名称不能为空');
}
// 2. Check Batch Quantity
const batchQuantityValue = batchQuantityInput.value;
if (batchQuantityValue === '' || !Number.isInteger(Number(batchQuantityValue)) || Number(batchQuantityValue) < 0) {
showValidationError(batchQuantityInput, '批量处理数量必须是非负整数');
isValid = false;
errors.push('批量处理数量必须是非负整数');
}
// 3. Check Steps
steps.forEach((step, index) => {
const stepIndexDisplay = index + 1;
// Check Step Name
if (!step.nameInput.value.trim()) {
showValidationError(step.nameInput, `步骤 ${stepIndexDisplay} 名称不能为空`);
isValid = false;
errors.push(`步骤 ${stepIndexDisplay} 名称不能为空`);
}
// Add listeners to step inputs dynamically if not already added
if (!step.nameInput.dataset.listenerAdded) {
step.nameInput.addEventListener('input', clearErrorOnInput);
step.nameInput.dataset.listenerAdded = 'true';
}
// Note: We are not validating start/work time based on requirements, only name
});
// 4. Check Cache Quantity (if applicable)
if (hasCacheCheckbox.checked) {
const cacheQuantityValue = cacheQuantityInput.value;
if (cacheQuantityValue === '' || !Number.isInteger(Number(cacheQuantityValue)) || Number(cacheQuantityValue) <= 0) {
showValidationError(cacheQuantityInput, '缓存数量必须是大于0的整数');
isValid = false;
errors.push('缓存数量必须是大于0的整数');
}
}
if (!isValid) {
// Optionally display a summary alert, though inline errors are better UX
// alert('请修正以下错误:\n- ' + errors.join('\n- '));
}
return isValid;
};
// Calculate Total Time and Theoretical PPM
const calculateMetrics = () => {
let totalDuration = 0;
let maxEndTime = 0;
steps.forEach(step => {
const startTime = parseFloat(step.startTimeInput.value) || 0;
const workTime = parseFloat(step.workTimeInput.value) || 0;
const endTime = startTime + workTime;
if (endTime > maxEndTime) {
maxEndTime = endTime;
}
});
totalDuration = maxEndTime;
totalTimeDisplay.textContent = totalDuration.toFixed(2);
const batchQuantityRaw = batchQuantityInput.value;
let batchQuantity = 1; // Default if invalid for calculation display
// Use valid integer for calculation, default to 1 if invalid or 0
if (batchQuantityRaw !== '' && Number.isInteger(Number(batchQuantityRaw)) && Number(batchQuantityRaw) > 0) {
batchQuantity = parseInt(batchQuantityRaw);
}
let calculatedPpm = 0;
if (totalDuration > 0) {
calculatedPpm = (60 / totalDuration) * batchQuantity;
}
calculatedPpmDisplay.textContent = calculatedPpm.toFixed(2);
};
// Update Step Titles (e.g., "步骤 1", "步骤 2")
const updateStepTitles = () => {
steps.forEach((step, index) => {
step.element.querySelector('.step-title').textContent = `步骤 ${index + 1}`;
step.element.dataset.index = index; // Update data-index for reordering
});
calculateMetrics(); // Recalculate when steps change order/number
};
// Create HTML for a single step
const createStepElement = (stepData = {}, index) => {
const stepId = `step-${Date.now()}-${Math.random()}`;
const stepDiv = document.createElement('div');
stepDiv.classList.add('step-item');
stepDiv.id = stepId;
stepDiv.dataset.index = index;
stepDiv.innerHTML = `
<div class="step-header">
<span class="step-title">步骤 ${index + 1}</span>
<div class="step-controls">
<button class="step-btn move-up-btn" title="上移">&#x2191;</button>
<button class="step-btn move-down-btn" title="下移">&#x2193;</button>
<button class="step-btn delete-step-btn" title="删除">&#x2716;</button>
</div>
</div>
<div class="step-inputs">
<div class="form-group">
<label for="step-name-${stepId}">名称:</label>
<input type="text" id="step-name-${stepId}" class="step-name-input" value="${stepData.name || `步骤${index + 1}`}" maxlength="12" required>
<span class="error-message step-error" id="step-name-error-${stepId}"></span>
</div>
<div class="form-group">
<label for="step-start-${stepId}">开始时间(秒):</label>
<input type="number" id="step-start-${stepId}" class="step-start-input" value="${stepData.startTime || 0}" min="0" step="0.1">
<span class="error-message step-error" id="step-start-error-${stepId}"></span>
</div>
<div class="form-group">
<label for="step-work-${stepId}">工作时间(秒):</label>
<input type="number" id="step-work-${stepId}" class="step-work-input" value="${stepData.workTime || 0}" min="0" step="0.1">
<span class="error-message step-error" id="step-work-error-${stepId}"></span>
</div>
</div>
`;
// Add event listeners for controls within this step
stepDiv.querySelector('.delete-step-btn').addEventListener('click', () => deleteStep(stepId));
stepDiv.querySelector('.move-up-btn').addEventListener('click', () => moveStep(stepId, -1));
stepDiv.querySelector('.move-down-btn').addEventListener('click', () => moveStep(stepId, 1));
// Add listeners to inputs for real-time calculation and error clearing
const nameInput = stepDiv.querySelector('.step-name-input');
const startTimeInput = stepDiv.querySelector('.step-start-input');
const workTimeInput = stepDiv.querySelector('.step-work-input');
[startTimeInput, workTimeInput, batchQuantityInput].forEach(input => {
input.addEventListener('input', calculateMetrics);
});
// Add input listener for validation clearing (only needed once per element)
if (!nameInput.dataset.listenerAdded) {
nameInput.addEventListener('input', clearErrorOnInput);
nameInput.dataset.listenerAdded = 'true';
}
return { element: stepDiv, id: stepId, nameInput, startTimeInput, workTimeInput };
};
// Add a new step
const addStep = (stepData = {}) => {
const newIndex = steps.length;
const newStep = createStepElement(stepData, newIndex);
stepsContainer.appendChild(newStep.element);
steps.push(newStep);
updateStepTitles();
};
// Delete a step
const deleteStep = (stepId) => {
const stepIndex = steps.findIndex(s => s.id === stepId);
if (stepIndex > -1) {
steps[stepIndex].element.remove();
steps.splice(stepIndex, 1);
updateStepTitles();
}
};
// Move a step up or down
const moveStep = (stepId, direction) => {
const index = steps.findIndex(s => s.id === stepId);
const newIndex = index + direction;
if (newIndex >= 0 && newIndex < steps.length) {
// Visual feedback
const currentElement = steps[index].element;
currentElement.classList.add('moving');
setTimeout(() => {
currentElement.classList.remove('moving');
// Also remove from the swapped element if it had the class briefly
if (steps[newIndex] && steps[newIndex].element) {
steps[newIndex].element.classList.remove('moving');
}
}, 300); // Match CSS transition duration
// Swap in the steps array
[steps[index], steps[newIndex]] = [steps[newIndex], steps[index]];
// Re-insert elements in the DOM based on the new order
stepsContainer.innerHTML = ''; // Clear container
steps.forEach(step => stepsContainer.appendChild(step.element)); // Re-append in new order
updateStepTitles();
}
};
// Toggle Cache Quantity Input
const toggleCacheInput = () => {
const isChecked = hasCacheCheckbox.checked;
cacheQuantityInput.disabled = !isChecked;
if (isChecked) {
cacheQuantityInput.required = true; // Make required when checked
} else {
cacheQuantityInput.required = false; // Not required when unchecked
cacheQuantityInput.value = ''; // Clear value when disabled
// Clear potential validation error when disabling
cacheQuantityInput.classList.remove('invalid');
const errorSpan = document.getElementById('cache-quantity-input-error');
if (errorSpan) {
errorSpan.textContent = '';
errorSpan.style.display = 'none';
}
}
};
// Open Settings Modal
const openModal = () => {
clearValidationErrors(); // Clear errors when opening
// Store current settings to revert on cancel
initialSettings = {
name: machineNameInput.value,
batchQuantity: batchQuantityInput.value,
hasCache: hasCacheCheckbox.checked,
cacheQuantity: cacheQuantityInput.value,
stepsData: steps.map(s => ({ // Only store values, not elements
name: s.nameInput.value,
startTime: s.startTimeInput.value,
workTime: s.workTimeInput.value
})),
// Store current display state
isActive: statusIndicator.classList.contains('active'),
isDisabled: statusIndicator.classList.contains('disabled'), // Store disabled state
statusText: machineStatus.textContent,
theoreticalPPM: theoreticalPpmDisplay.textContent, // Store the actual text content
currentStep: document.getElementById('current-step').textContent,
currentPPM: document.getElementById('current-ppm').textContent
};
// Update modal title
modalTitle.textContent = `编辑-${initialSettings.name || '一般机构'}`;
settingsModal.style.display = 'flex';
calculateMetrics(); // Ensure calculations are up-to-date when opening
};
// Close Settings Modal
const closeModal = () => {
settingsModal.style.display = 'none';
};
// Revert settings to initial state (on cancel or 'X' click)
const revertSettings = () => {
clearValidationErrors(); // Clear validation errors on revert/cancel
machineNameInput.value = initialSettings.name;
batchQuantityInput.value = initialSettings.batchQuantity;
hasCacheCheckbox.checked = initialSettings.hasCache;
cacheQuantityInput.value = initialSettings.cacheQuantity;
toggleCacheInput(); // This also handles required attribute
// Rebuild steps from initial data
stepsContainer.innerHTML = '';
steps = [];
initialSettings.stepsData.forEach(stepData => addStep(stepData));
// Revert main display state using the helper function for status
machineNameDisplay.textContent = initialSettings.name;
theoreticalPpmDisplay.textContent = initialSettings.theoreticalPPM; // Use stored text
updateMachineStatus(initialSettings.statusText); // This updates text AND indicator class
document.getElementById('current-step').textContent = initialSettings.currentStep;
document.getElementById('current-ppm').textContent = initialSettings.currentPPM;
closeModal();
};
// Save Settings
const saveSettings = () => {
if (!validateSettings()) {
console.log("Validation failed."); // Debug log
// Optionally show a general error message at the top/bottom?
// alert("请检查表单中的错误并修正。");
return; // Stop saving if validation fails
}
console.log("Validation passed."); // Debug log
// Validation passed, proceed with saving
const newName = machineNameInput.value.trim();
const batchQty = parseInt(batchQuantityInput.value); // Already validated as integer
machineNameDisplay.textContent = newName;
calculateMetrics(); // Recalculate with potentially changed batch qty
theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM';
// Update status based on batch quantity
if (batchQty === 0) {
updateMachineStatus('禁用中');
} else {
// Set to '运行中' or potentially another state based on future logic
// For now, assume it goes to '运行中' if not disabled
updateMachineStatus('运行中');
}
// Update current step/ppm (example) - might need real logic later
document.getElementById('current-step').textContent = steps.length > 0 ? steps[0].nameInput.value : '无步骤';
document.getElementById('current-ppm').textContent = '0.00PPM'; // Reset or calculate actual current
closeModal();
};
// --- Event Listeners ---
machineComponent.addEventListener('dblclick', openModal);
closeModalBtn.addEventListener('click', revertSettings);
cancelSettingsBtn.addEventListener('click', revertSettings);
saveSettingsBtn.addEventListener('click', saveSettings);
addStepBtn.addEventListener('click', () => addStep());
hasCacheCheckbox.addEventListener('change', toggleCacheInput);
// Add listeners to clear errors on input for main fields
machineNameInput.addEventListener('input', clearErrorOnInput);
batchQuantityInput.addEventListener('input', clearErrorOnInput);
cacheQuantityInput.addEventListener('input', clearErrorOnInput);
// --- Initialization ---
const initialize = () => {
// Add default steps as per the image
addStep({ name: '步骤1', startTime: 0, workTime: 3 });
addStep({ name: '步骤2', startTime: 2, workTime: 3 });
// Set initial values based on the image (or defaults)
machineNameInput.value = '一般机构';
batchQuantityInput.value = 1;
hasCacheCheckbox.checked = true; // From image
cacheQuantityInput.value = 3; // From image
toggleCacheInput(); // Enable/disable and set required
// Initial calculation and display update
machineNameDisplay.textContent = machineNameInput.value;
calculateMetrics();
theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM';
// Set default component state (can be customized)
document.getElementById('current-step').textContent = '步骤1'; // Example
document.getElementById('current-ppm').textContent = '0.00PPM'; // Example
updateMachineStatus('等待中'); // Use helper to set initial status
// Store initial theoretical PPM text correctly for revert
if (!initialSettings.theoreticalPPM) { // Ensure it's set only once initially
initialSettings.theoreticalPPM = theoreticalPpmDisplay.textContent;
}
// Clear any potential initial validation states on load
clearValidationErrors();
};
initialize();
});
@@ -0,0 +1,679 @@
/* 全局和页面基础样式 */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f6; /* 页面背景色 */
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
min-height: 100vh;
margin: 0;
}
/* --- 主组件显示区域样式 --- */
.machine-component {
background-color: #ffffff; /* 组件背景色 */
border-radius: 12px; /* 圆角 */
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 阴影 */
padding: 15px; /* Adjusted padding */
max-width: 350px; /* Max width on larger screens */
width: 90%; /* Relative width on smaller screens */
margin: 10px; /* Add some margin */
cursor: pointer; /* 鼠标样式 */
transition: box-shadow 0.3s ease; /* 阴影过渡效果 */
border: 1px solid #e0e0e0; /* 边框 */
}
.machine-component:hover {
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); /* 鼠标悬浮时阴影加强 */
}
/* 主组件头部 */
.header {
display: flex;
justify-content: space-between; /* 两端对齐 */
align-items: center; /* 垂直居中 */
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid #eee; /* 底部边框分割线 */
}
/* 主组件 - 机构名称 */
#machine-name-display {
font-size: 1.2em;
font-weight: 600;
color: #333;
}
/* 主组件 - 状态指示灯 */
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%; /* 圆形 */
background-color: #ffc107; /* Default Yellow for waiting */
transition: background-color 0.3s ease; /* Keep transition for color change */
/* Apply default yellow pulse animation */
animation: pulse-yellow 1.5s infinite;
}
/* Active state overrides */
.status-indicator.active {
background-color: #4CAF50; /* Green when active */
animation-name: pulse-green; /* Change animation name */
}
/* Disabled state overrides */
.status-indicator.disabled {
background-color: #dc3545; /* Red when disabled */
animation-name: pulse-red; /* Use red pulse */
}
/* Define the GREEN pulse animation */
@keyframes pulse-green {
0% {
box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.5); /* Green shadow */
}
70% {
box-shadow: 0 0 0 8px rgba(76, 175, 80, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(76, 175, 80, 0);
}
}
/* Define the YELLOW pulse animation */
@keyframes pulse-yellow {
0% {
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.5); /* Yellow shadow */
}
70% {
box-shadow: 0 0 0 8px rgba(255, 193, 7, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
}
}
/* Define the RED pulse animation */
@keyframes pulse-red {
0% {
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.5); /* Red shadow */
}
70% {
box-shadow: 0 0 0 8px rgba(220, 53, 69, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0);
}
}
/* 主组件 - 信息网格布局 */
.info-grid {
display: grid;
grid-template-columns: auto 1fr; /* 标签自适应,值占满剩余空间 */
gap: 8px 15px; /* 行间距 列间距 */
margin-bottom: 15px;
font-size: 0.95em;
}
/* 主组件 - 信息标签 */
.info-label {
color: #555;
font-weight: 500;
text-align: right; /* 文本右对齐 */
}
/* 主组件 - 信息值 */
.info-value {
color: #333;
font-weight: 600;
}
/* 主组件 - 底部状态文本 */
.status-text {
text-align: center;
font-weight: 500;
color: #666;
padding-top: 10px;
border-top: 1px solid #eee; /* 顶部边框分割线 */
font-size: 0.9em;
}
/* --- 设置弹窗 (Modal) 样式 --- */
/* 弹窗遮罩层 */
.modal-overlay {
position: fixed; /* 固定定位,覆盖全屏 */
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
display: flex;
justify-content: center; /* 水平居中弹窗内容 */
align-items: center; /* 垂直居中弹窗内容 */
z-index: 1000; /* 置于顶层 */
}
/* 弹窗内容区域 */
.modal-content {
background-color: #fff;
border-radius: 10px; /* 圆角 */
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
max-width: 600px; /* Max width on larger screens */
width: 90vw; /* Relative width */
max-height: 90vh; /* 最大高度为视窗的90% */
display: flex; /* Use flexbox for layout */
flex-direction: column; /* Stack header, scroll, footer vertically */
overflow: hidden; /* Re-add overflow hidden to clip children and enforce height */
}
/* Remove scrollbar styles from .modal-content */
/*
.modal-content::-webkit-scrollbar { ... }
.modal-content::-webkit-scrollbar-track { ... }
.modal-content::-webkit-scrollbar-thumb { ... }
.modal-content::-webkit-scrollbar-thumb:hover { ... }
*/
/* Fixed Header Section */
.modal-fixed-header {
padding: 20px 25px 0 25px; /* Padding T, R/L, B */
border-bottom: 1px solid #eee; /* Separator */
}
.steps-legend {
/* Styles for the moved legend */
font-weight: 600;
color: #333;
padding: 10px 0 5px 0; /* Adjust padding */
margin: 0; /* Remove default legend margin */
font-size: 1.1em; /* Match step-title size */
}
/* Scrollable Steps Area */
.modal-scrollable-steps {
flex-grow: 1; /* Allow this section to take available vertical space */
overflow-y: auto; /* Enable vertical scrolling ONLY for this section */
padding: 15px 25px; /* Padding inside the scrollable area */
/* Apply custom scrollbar styles HERE */
scrollbar-width: thin; /* Firefox */
scrollbar-color: #ccc #f4f4f4; /* Firefox */
}
.modal-scrollable-steps::-webkit-scrollbar {
width: 8px;
}
.modal-scrollable-steps::-webkit-scrollbar-track {
background: #f4f4f4;
border-radius: 10px;
margin: 5px 0; /* Add slight margin */
}
.modal-scrollable-steps::-webkit-scrollbar-thumb {
background-color: #ccc;
border-radius: 10px;
border: 2px solid #f4f4f4;
}
.modal-scrollable-steps::-webkit-scrollbar-thumb:hover {
background-color: #aaa;
}
/* Fixed Footer Section */
.modal-fixed-footer {
padding: 10px 25px 20px 25px; /* Padding T, R/L, B */
border-top: 1px solid #eee; /* Separator */
background-color: #fff; /* Ensure solid background */
}
/* Adjustments for items moved to footer */
.modal-fixed-footer .add-btn {
margin-top: 10px; /* Adjust top margin */
margin-bottom: 15px; /* Add bottom margin */
}
.modal-fixed-footer .cache-group {
margin-bottom: 15px; /* Add consistent margin */
}
.modal-fixed-footer .summary-section {
margin-top: 15px; /* Adjust top margin */
padding-top: 0; /* Remove padding as border is above */
border-top: none; /* Remove border as it's on footer now */
}
.modal-fixed-footer .modal-footer {
margin-top: 15px; /* Adjust top margin */
padding-top: 0; /* Remove padding as border is above */
border-top: none; /* Remove border as it's on footer now */
}
/* Remove original steps-config styling */
/*
.steps-config { ... }
.steps-config legend { ... }
*/
/* 弹窗头部 */
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
margin-bottom: 20px;
}
/* 弹窗标题 */
#modal-title {
font-size: 1.4em;
font-weight: 600;
color: #333;
}
/* 弹窗关闭按钮 */
.close-btn {
background: none;
border: none;
font-size: 1.8em;
cursor: pointer;
color: #888;
}
.close-btn:hover {
color: #333;
}
/* 弹窗主体内容区域 */
.modal-body {
margin-bottom: 20px;
}
/* 通用表单组样式 */
.form-group {
margin-bottom: 15px;
display: grid;
grid-template-columns: 120px 1fr; /* 标签固定宽度,输入框占满剩余 - Default */
align-items: center;
gap: 5px 10px; /* Reduced gap slightly */
}
/* 表单标签 */
.form-group label {
font-weight: 500;
color: #555;
text-align: right;
}
/* 表单输入框 (文本和数字) */
.form-group input[type="text"],
.form-group input[type="number"] {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 0.95em;
transition: border-color 0.3s ease;
}
/* 输入框获取焦点时样式 */
.form-group input[type="text"]:focus,
.form-group input[type="number"]:focus {
border-color: #007bff; /* 边框变蓝 */
outline: none; /* 移除默认轮廓 */
}
/* 禁用的数字输入框 */
.form-group input[type="number"][disabled] {
background-color: #e9ecef;
cursor: not-allowed;
}
/* --- 步骤设置区域 --- */
.steps-config {
border: 1px solid #ddd; /* 边框 */
border-radius: 8px; /* 圆角 */
padding: 15px;
margin-bottom: 20px;
}
/* 步骤设置区域标题 */
.steps-config legend {
font-weight: 600;
color: #333;
padding: 0 10px;
}
/* 单个步骤项 */
.step-item {
border: 1px dashed #ccc; /* 虚线边框 */
border-radius: 6px;
padding: 15px;
margin-bottom: 15px;
position: relative;
background-color: #f9f9f9;
}
/* 步骤项头部 */
.step-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
/* 步骤标题 (如: 步骤 1) */
.step-title {
font-weight: bold;
font-size: 1.1em;
}
/* 步骤控制按钮组 (上移/下移/删除) */
.step-controls {
display: flex;
gap: 5px;
}
/* 步骤控制按钮通用样式 */
.step-btn {
background: none;
border: none;
cursor: pointer;
font-size: 1.2em;
color: #888;
}
.step-btn:hover { color: #333; }
/* 删除按钮特定颜色 */
.delete-step-btn { color: #dc3545; }
.delete-step-btn:hover { color: #a71d2a; }
/* 步骤内部输入框布局 */
.step-inputs {
display: grid;
grid-template-columns: auto 1fr 1fr; /* 名称自适应,时间占剩余空间 - Default */
gap: 10px;
align-items: start; /* 顶部对齐 */
}
/* 步骤内表单组 */
.step-inputs .form-group {
grid-template-columns: 1fr; /* 内部标签和输入框垂直排列 */
margin-bottom: 0;
gap: 3px;
}
/* 步骤内标签样式 */
.step-inputs label {
text-align: left;
font-size: 0.85em;
margin-bottom: 2px;
color: #666;
display: block; /* 确保独占一行 */
white-space: nowrap; /* 防止标签换行 */
overflow: hidden; /* 隐藏超出部分 */
text-overflow: ellipsis; /* 超出部分显示省略号 */
max-width: 100%; /* 防止标签撑开布局 */
}
/* 限制步骤内时间输入框的最大宽度 */
.step-inputs .form-group:nth-child(2) input[type="number"],
.step-inputs .form-group:nth-child(3) input[type="number"] {
max-width: 85px; /* 最大宽度限制 */
width: 100%; /* 允许在容器缩小时也缩小 */
}
/* 确保步骤内名称输入框填满其列 */
.step-inputs .form-group:nth-child(1) input[type="text"] {
width: 85%;
}
/* --- 其他设置和按钮 --- */
/* 添加步骤按钮 */
.add-btn {
padding: 8px 15px;
background-color: #28a745;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 0.95em;
transition: background-color 0.3s ease;
margin-top: 15px;
/* 居中显示 */
display: block;
width: fit-content; /* 宽度自适应内容 */
margin-left: auto;
margin-right: auto;
}
.add-btn:hover {
background-color: #218838;
}
/* 缓存设置组 */
.cache-group {
display: grid; /* Use grid for better control with errors */
grid-template-columns: auto auto 1fr; /* checkbox, label, input - Default */
align-items: center;
gap: 10px;
}
/* 缓存复选框 */
.cache-group input[type="checkbox"] { grid-row: 1; }
.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; }
.cache-group input[type="number"] { grid-row: 1; }
.cache-group .error-message {
grid-column: 3; /* Error below the number input */
grid-row: 2;
margin-top: 2px;
}
/* 汇总信息区域 */
.summary-section {
margin-top: 20px;
padding-top: 15px;
border-top: 1px solid #eee;
display: flex;
justify-content: space-around; /* 两端分散对齐 */
font-size: 0.95em;
color: #555;
}
/* 汇总信息中的数值 */
.summary-section span span {
font-weight: 600;
color: #333;
}
/* 弹窗底部按钮区域 */
.modal-footer {
display: flex;
justify-content: flex-end; /* 按钮靠右对齐 */
gap: 10px;
padding-top: 15px;
border-top: 1px solid #eee;
margin-top: 20px;
}
/* 保存和取消按钮通用样式 */
.save-btn,
.cancel-btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s ease, color 0.3s ease;
}
/* 保存按钮 */
.save-btn {
background-color: #007bff;
color: white;
}
.save-btn:hover {
background-color: #0056b3;
}
/* 取消按钮 */
.cancel-btn {
background-color: #f8f9fa;
color: #333;
border: 1px solid #ccc;
}
.cancel-btn:hover {
background-color: #e2e6ea;
}
/* --- 工具类样式 --- */
/* 错误消息 (未使用,可备用) */
.error-message {
color: #dc3545;
font-size: 0.85em; /* Slightly larger */
padding-left: 0; /* Remove padding */
display: none; /* Hidden by default */
margin-top: 2px; /* Add small top margin */
}
/* Ensure error message appears below input in standard form groups */
.form-group .error-message {
grid-column: 2; /* Align with input */
grid-row: 2; /* Place on the row below the input */
text-align: left;
}
/* Error messages within steps */
.step-inputs .error-message {
/* display: block; */ /* Already block by default */
width: 100%; /* Take full width */
margin-top: 2px;
text-align: left;
}
/* Adjust cache group alignment when error shows */
.cache-group {
display: grid; /* Use grid for better control with errors */
grid-template-columns: auto auto 1fr; /* checkbox, label, input */
align-items: center;
gap: 10px;
}
.cache-group input[type="checkbox"] { grid-row: 1; }
.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; }
.cache-group input[type="number"] { grid-row: 1; }
.cache-group .error-message {
grid-column: 3; /* Error below the number input */
grid-row: 2;
margin-top: 2px;
}
/* 步骤项移动时的视觉反馈 */
.step-item.moving {
transition: background-color 0.3s ease-out;
background-color: #e6f7ff; /* 淡蓝色高亮 */
}
/* Input Validation Styles */
input:invalid,
textarea:invalid {
border-color: #dc3545; /* Red border for invalid fields */
}
.form-group input.invalid,
.step-item input.invalid {
border-color: #dc3545 !important; /* Force red border */
background-color: #fff3f3; /* Light red background */
}
.error-tooltip {
color: #dc3545;
font-size: 0.8em;
padding-left: 5px;
display: none; /* Hidden by default */
}
.form-group .error-tooltip {
grid-column: 2; /* Align with input in main form groups */
}
/* --- Responsive Adjustments --- */
@media (max-width: 600px) {
/* Reduce padding/font size slightly globally in modal? Optional */
.modal-content {
width: 95vw; /* Use more width on mobile */
max-height: 95vh; /* Allow slightly more height */
}
.modal-fixed-header,
.modal-scrollable-steps,
.modal-fixed-footer {
padding: 15px; /* Consistent padding */
}
/* Stack form groups vertically */
.form-group {
grid-template-columns: 1fr; /* Single column */
gap: 5px; /* Reduce gap */
}
.form-group label {
text-align: left; /* Align labels left */
margin-bottom: 2px;
}
/* Ensure error messages span full width below input */
.form-group .error-message {
grid-column: 1; /* Span full column */
grid-row: 3; /* Ensure it's below label and input */
}
/* Stack step inputs vertically */
.step-inputs {
grid-template-columns: 1fr; /* Single column */
gap: 10px;
}
/* Allow time inputs to take more width when stacked */
.step-inputs .form-group:nth-child(2) input[type="number"],
.step-inputs .form-group:nth-child(3) input[type="number"] {
max-width: none; /* Remove max-width limit */
}
/* Stack cache group elements */
.cache-group {
grid-template-columns: auto 1fr; /* Checkbox | Label & Input */
gap: 5px 10px;
}
.cache-group input[type="checkbox"] { grid-row: 1; grid-column: 1; }
.cache-group label[for="has-cache-checkbox"] { grid-row: 1; grid-column: 2; }
.cache-group input[type="number"] { grid-row: 2; grid-column: 1 / span 2; width: 100%;} /* Input below */
.cache-group .error-message {
grid-row: 3; /* Error below input */
grid-column: 1 / span 2;
}
/* Stack summary section */
.summary-section {
flex-direction: column; /* Stack items */
align-items: center; /* Center align */
gap: 5px;
}
/* Adjust footer buttons */
.modal-footer {
justify-content: space-around; /* Space out buttons more */
}
.save-btn,
.cancel-btn {
padding: 8px 15px; /* Slightly smaller buttons */
font-size: 0.95em;
}
}
+15
View File
@@ -0,0 +1,15 @@
# README
1. 组件库
| / | 前段设备 | 常规机构 | 缓存机构 | 集装夹具 | 运输机构 | 仓储机构 | 后段设备 |
|:--------:|----------------------------------------|----------------------------------------------------|---------------------|------|------|------|------|
| 组件形状 | 椭圆形 | 圆角矩形 | 圆角矩形 | 圆角矩形 | 菱形 | 图表 | 椭圆形 |
| 组件外框颜色 | 蓝色 | 绿色 | 黄色 | 橙色 | 青色 | 黑色 | 红色 |
| 组件内文字示例 | 组件名称:前段设备1 投入总数:100 不良品数:2 当前状态:等待后续机构 | 组件名称:常规机构1 当前状态:工作中 当前步骤:步骤1 理论产能:60PPM 实时产能:50PPM | 组件名称:缓存机构1 当前状态:工作中 | | | | |
| 双击设置项 | | | | | | | |
| 功能 | | | | | | | |
| 组件时序计算逻辑 | | | | | | | |
| 流程中仿真逻辑 | | | | | | | |
| 连接点 | | | | | | | |
| 其他 | | | | | | | |
+178
View File
@@ -0,0 +1,178 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>流程图仿真工具</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="sidebar">
<h2>图形库</h2>
<div class="shape-container">
<div class="shape-group">
<h3>机构类型</h3>
<div class="shape-item" draggable="true" data-shape-type="start">
<div class="start-shape">开始</div>
</div>
<div class="shape-item" draggable="true" data-shape-type="process">
<div class="process-shape">普通机构</div>
</div>
<div class="shape-item" draggable="true" data-shape-type="transport">
<div class="transport-shape">运输机构</div>
</div>
<div class="shape-item" draggable="true" data-shape-type="endpoint">
<div class="endpoint-shape">收料机构</div>
</div>
</div>
</div>
<div class="control-panel">
<button id="start-simulation">开始仿真</button>
<button id="stop-simulation">停止仿真</button>
<button id="reset-simulation">重置</button>
<!-- 仿真设置已移除,完全按照机构的实际速度进行仿真 -->
<div class="project-actions">
<button id="save-project">保存项目</button>
<button id="load-project">加载项目</button>
</div>
</div>
<div class="simulation-info">
<h3>仿真数据</h3>
<div id="simulation-stats">
<div>模拟时间: <span id="elapsed-time">0.0</span> 秒</div>
<div>系统产能: <span id="system-throughput">0.0</span> 个/秒</div>
<div>总产出: <span id="total-output">0</span> 个</div>
</div>
</div>
</div>
<div class="main-content">
<div class="canvas-container">
<canvas id="flow-canvas"></canvas>
</div>
<div class="status-bar">
<div id="status-message">就绪</div>
<div id="zoom-controls">
<button id="zoom-in">+</button>
<span id="zoom-level">100%</span>
<button id="zoom-out">-</button>
</div>
</div>
</div>
</div>
<!-- 图形编辑弹窗 -->
<div id="shape-modal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2 id="modal-title">编辑机构</h2>
<form id="shape-form">
<div class="form-group">
<label for="shape-name">机构名称:</label>
<input type="text" id="shape-name" required>
</div>
<!-- 普通机构参数 -->
<div id="process-params">
<div class="form-group">
<label for="batch-size">批量处理数量:</label>
<input type="number" id="batch-size" min="1" value="1" required>
</div>
<div class="form-group">
<label>步骤设置:</label>
<div id="steps-container">
<!-- 步骤将在这里动态添加 -->
</div>
<div class="steps-actions">
<button type="button" id="add-step" class="add-btn">添加步骤</button>
</div>
</div>
<div class="form-group">
<label>总耗时: <span id="total-time">0</span> 秒</label>
</div>
</div>
<!-- 运输机构参数 -->
<div id="transport-params" style="display:none;">
<div class="form-group">
<label for="transport-time">单次搬运时间(秒):</label>
<input type="number" id="transport-time" min="0.1" step="0.1" value="2.0" required>
</div>
<div class="form-group">
<label for="transport-batch">每次搬运数量:</label>
<input type="number" id="transport-batch" min="1" value="1" required>
</div>
<div class="form-group">
<label for="transport-count">搬运次数:</label>
<input type="number" id="transport-count" min="1" value="1" required>
</div>
</div>
<!-- 收料机构参数 -->
<div id="endpoint-params" style="display:none;">
<div class="form-group">
<label for="collection-capacity">收集容量:</label>
<input type="number" id="collection-capacity" min="1" value="100" required>
</div>
</div>
<div class="form-actions">
<button type="submit">保存</button>
<button type="button" id="cancel-edit">取消</button>
</div>
</form>
</div>
</div>
<!-- 连接编辑弹窗 -->
<div id="connection-modal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2>编辑连接</h2>
<form id="connection-form">
<div class="form-group">
<label for="connection-delay">传输延迟(秒):</label>
<input type="number" id="connection-delay" min="0" step="0.1" value="0" required>
</div>
<div class="form-actions">
<button type="submit">保存</button>
<button type="button" id="cancel-connection-edit">取消</button>
<button type="button" id="delete-connection" class="delete-btn">删除连接</button>
</div>
</form>
</div>
</div>
<!-- 文件操作模态框 -->
<div id="file-modal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2 id="file-modal-title">保存项目</h2>
<form id="file-form">
<div class="form-group">
<label for="project-name">项目名称:</label>
<input type="text" id="project-name" required>
</div>
<div class="form-actions">
<button type="submit" id="file-action-btn">保存</button>
<button type="button" id="cancel-file-action">取消</button>
</div>
</form>
<div id="saved-projects-container" style="display:none;">
<h3>已保存的项目</h3>
<ul id="saved-projects-list">
<!-- 已保存的项目将在这里显示 -->
</ul>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+684
View File
@@ -0,0 +1,684 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Microsoft YaHei', sans-serif;
background-color: #f5f5f5;
color: #333;
}
.container {
display: flex;
height: 100vh;
overflow: hidden;
}
/* 侧边栏样式 */
.sidebar {
width: 300px;
background-color: #fff;
border-right: 1px solid #ddd;
padding: 15px;
display: flex;
flex-direction: column;
overflow-y: auto;
}
.sidebar h2, .sidebar h3 {
margin-bottom: 15px;
color: #333;
text-align: center;
}
.sidebar h3 {
margin: 10px 0;
font-size: 16px;
border-bottom: 1px solid #eee;
padding-bottom: 5px;
}
/* 图形库样式 */
.shape-container {
margin-bottom: 20px;
}
.shape-group {
margin-bottom: 15px;
}
.shape-item {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
margin-bottom: 8px;
cursor: grab;
user-select: none;
background-color: #f9f9f9;
transition: all 0.2s;
}
.shape-item:hover {
background-color: #e3f2fd;
border-color: #2196F3;
}
.shape-item:active {
cursor: grabbing;
}
/* 图形样式 */
.start-shape {
width: 100%;
height: 40px;
background-color: #fff;
border: 2px solid #ff0000;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
position: relative;
text-align: center;
}
.start-shape::after {
content: "";
position: absolute;
right: -6px;
top: 50%;
transform: translateY(-50%);
width: 12px;
height: 12px;
background-color: #ff0000;
border-radius: 50%;
}
.process-shape {
width: 100%;
height: 40px;
background-color: #fff;
border: 2px solid #4CAF50;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
}
.transport-shape {
width: 80px;
height: 40px;
margin: 0 auto;
position: relative;
background-color: #fff;
border: none;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
}
.transport-shape::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 2px solid #FF9800;
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
.endpoint-shape {
width: 100px;
height: 40px;
margin: 0 auto;
background-color: #fff;
border: 2px solid #9C27B0;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
}
/* 控制面板样式 */
.control-panel {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 15px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
.control-panel button {
padding: 8px 12px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
.control-panel button:hover {
background-color: #45a049;
}
#stop-simulation {
background-color: #f44336;
}
#stop-simulation:hover {
background-color: #d32f2f;
}
#reset-simulation {
background-color: #2196F3;
}
#reset-simulation:hover {
background-color: #1976D2;
}
.simulation-settings {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid #ddd;
}
.project-actions {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid #ddd;
display: flex;
gap: 10px;
}
.project-actions button {
flex: 1;
background-color: #673AB7;
}
.project-actions button:hover {
background-color: #5E35B1;
}
/* 仿真信息样式 */
.simulation-info {
margin-top: 15px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
#simulation-stats {
margin-top: 10px;
font-size: 14px;
}
#simulation-stats div {
margin-bottom: 5px;
}
#simulation-stats span {
font-weight: bold;
color: #FF5722;
}
/* 主内容区域样式 */
.main-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.canvas-container {
flex: 1;
position: relative;
background-color: #f1f1f1;
overflow: hidden;
background-image: linear-gradient(#ddd 1px, transparent 1px),
linear-gradient(90deg, #ddd 1px, transparent 1px);
background-size: 20px 20px;
}
#flow-canvas {
width: 100%;
height: 100%;
cursor: grab;
}
#flow-canvas:active {
cursor: grabbing;
}
/* 状态栏样式 */
.status-bar {
height: 30px;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
}
#status-message {
font-size: 14px;
color: #666;
}
#zoom-controls {
display: flex;
align-items: center;
gap: 5px;
}
#zoom-controls button {
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
background-color: #f1f1f1;
border: 1px solid #ddd;
border-radius: 3px;
cursor: pointer;
}
#zoom-controls button:hover {
background-color: #e0e0e0;
}
#zoom-level {
font-size: 14px;
color: #666;
width: 50px;
text-align: center;
}
/* 模态框样式 */
.modal {
display: none;
position: fixed;
z-index: 100;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
.modal-content {
background-color: #fff;
margin: 10% auto;
padding: 20px;
border-radius: 5px;
width: 60%;
max-width: 600px;
max-height: 80vh;
overflow-y: auto;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover {
color: #333;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.form-group input,
.form-group select {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.form-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 20px;
}
.form-actions button {
padding: 8px 15px;
border-radius: 4px;
cursor: pointer;
}
.form-actions button[type="submit"] {
background-color: #4CAF50;
color: white;
border: none;
}
.form-actions button[type="button"] {
background-color: #f1f1f1;
border: 1px solid #ddd;
}
.delete-btn {
background-color: #f44336 !important;
color: white !important;
}
.add-btn {
background-color: #4CAF50 !important;
color: white !important;
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
.step-item {
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
margin-bottom: 10px;
position: relative;
background-color: #f9f9f9;
}
.step-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.step-title {
font-weight: bold;
}
.step-remove {
background-color: #f44336;
color: white;
border: none;
border-radius: 50%;
width: 24px;
height: 24px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
}
.step-content {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.step-field {
flex: 1;
min-width: 100px;
}
.steps-actions {
margin-top: 10px;
text-align: center;
}
/* 画布上的图形和连接样式 */
.flow-shape {
position: absolute;
cursor: move;
user-select: none;
}
.flow-start {
width: 160px;
height: 80px;
background-color: white;
border: 2px solid #ff0000;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
position: relative;
text-align: center;
padding: 0;
}
.flow-start::after {
content: "";
position: absolute;
right: -6px;
top: 50%;
transform: translateY(-50%);
width: 12px;
height: 12px;
background-color: #ff0000;
border-radius: 50%;
}
.flow-process {
width: 160px;
height: 80px;
background-color: white;
border: 2px solid #4CAF50;
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.flow-transport {
width: 140px;
height: 80px;
background-color: white;
border: none;
transform: rotate(0deg);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
}
.flow-transport::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 2px solid #FF9800;
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
.flow-endpoint {
width: 160px;
height: 80px;
background-color: white;
border: 2px solid #9C27B0;
border-radius: 40px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.shape-title {
font-weight: bold;
margin-bottom: 5px;
max-width: 90%;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.shape-info {
font-size: 12px;
color: #666;
margin-bottom: 2px;
}
.shape-throughput {
font-size: 13px;
color: #FF5722;
font-weight: bold;
}
.connection-point {
position: absolute;
width: 16px;
height: 16px;
background-color: #2196F3;
border-radius: 50%;
cursor: pointer;
z-index: 100;
transition: transform 0.2s, background-color 0.2s;
}
.connection-point:hover {
transform: scale(1.3);
background-color: #1976D2;
}
.connection-point.output {
right: 0;
top: 50%;
transform: translate(50%, -50%);
}
.connection-point.input {
left: 0;
top: 50%;
transform: translate(-50%, -50%);
}
.connection-helper {
position: absolute;
width: 24px;
height: 24px;
background-color: rgba(33, 150, 243, 0.3);
border-radius: 50%;
border: 2px solid #2196F3;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
cursor: pointer;
z-index: 10;
transform: translate(-50%, -50%);
}
.connection-helper:hover {
background-color: rgba(33, 150, 243, 0.6);
}
/* 连接线样式 */
.connection-line {
stroke: #2196F3;
stroke-width: 2;
fill: none;
}
.connection-arrow {
fill: #2196F3;
}
.connection-label {
font-size: 12px;
fill: #333;
text-anchor: middle;
dominant-baseline: central;
}
.connection-label-bg {
fill: white;
stroke: #ddd;
stroke-width: 1;
rx: 3;
ry: 3;
}
/* 物料流动动画 */
.material-particle {
fill: #FF9800;
stroke: #F57C00;
stroke-width: 1;
}
/* 已保存项目列表样式 */
#saved-projects-list {
list-style: none;
margin-top: 10px;
}
#saved-projects-list li {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 5px;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
}
#saved-projects-list li:hover {
background-color: #e3f2fd;
}
#saved-projects-list .project-actions {
display: flex;
gap: 5px;
border: none;
margin: 0;
padding: 0;
}
#saved-projects-list .project-actions button {
padding: 3px 6px;
font-size: 12px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.sidebar {
width: 100%;
height: 300px;
}
.modal-content {
width: 90%;
}
}
+699
View File
@@ -0,0 +1,699 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>机械设计云平台</title>
<!-- 添加Iconify脚本 -->
<script src="https://code.iconify.design/iconify-icon/1.0.7/iconify-icon.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Arial', sans-serif;
display: flex;
height: 100vh;
}
/* 为图标添加样式 */
.nav-button iconify-icon {
margin-right: 8px;
vertical-align: middle;
}
.header-title iconify-icon {
margin-right: 8px;
vertical-align: middle;
}
/* 侧边栏样式 */
.sidebar {
width: 220px;
background-color: #FFFFFF;
display: flex;
flex-direction: column;
padding: 20px;
box-shadow: 2px 0 5px rgba(0,0,0,0.05);
}
.logo {
height: 80px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 30px;
}
.logo img {
max-width: 150px;
}
.nav-buttons {
flex-grow: 1;
overflow-y: auto;
}
.nav-button {
display: flex;
align-items: center;
width: 100%;
padding: 12px 15px;
margin-bottom: 10px;
background-color: #FFFFFF;
color: #4B5563;
border: none;
text-align: left;
cursor: pointer;
border-radius: 8px;
transition: all 0.3s ease;
font-weight: 600;
font-size: 15px;
}
.nav-button:hover {
background-color: #F3F4F6;
}
/* 激活按钮样式,显示竖线 */
.nav-button.active::before {
content: '';
display: block;
width: 3px;
height: 20px; /* 竖线的高度,比按钮的高度短 */
background-color: green;
margin-right: 15px; /* 留出空间与按钮文字分开 */
}
.nav-button.active {
background-color: #F3F4F6;
color: #1F2937;
}
.user-info {
display: flex;
align-items: center;
padding: 15px;
background-color: #FFFFFF;
}
.user-avatar {
width: 50px;
height: 50px;
border-radius: 50%;
margin-right: 10px;
background-color: #E5E7EB;
position: relative;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.user-avatar:hover {
background-color: #F3F4F6;
}
.login-register {
position: relative;
cursor: pointer;
color: #4B5563;
transition: color 0.3s ease;
}
.login-register:hover {
color: #1F2937;
}
.main-content {
flex-grow: 1;
display: flex;
flex-direction: column;
position: relative;
}
.header {
height: 60px;
background-color: #FFFFFF;
display: flex;
align-items: center;
padding: 0 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.header-title {
flex-grow: 1;
font-weight: bold;
color: #1F2937;
font-size: 18px;
display: flex;
align-items: center;
}
.header-settings {
cursor: pointer;
color: #4B5563;
}
.settings-button {
background-color: #262E45;
color: #FFFFFF;
border: none;
padding: 8px 15px;
border-radius: 6px;
font-size: 15px;
font-weight: 600;
margin-left: 10px;
cursor: pointer;
transition: background-color 0.3s ease;
display: flex;
align-items: center;
}
.settings-button:hover {
background-color: #3B4563;
}
.content-area {
flex-grow: 1;
padding: 20px;
background-color: #EFF4F9;
position: relative;
}
.function-zone {
position: absolute;
left: calc(10px);
top: calc(10px);
right: 10px;
bottom: 10px;
background-color: #FFFFFF;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
padding: 20px;
overflow: auto;
}
.status-bar {
height: 40px;
background-color: #FFFFFF;
color: #6B7280;
display: flex;
justify-content: flex-end;
align-items: center;
padding: 0 20px;
font-size: 12px;
box-shadow: 0 -2px 4px rgba(0,0,0,0.05);
}
.settings-button span {
margin-left: 5px; /* Adjusted space between icon and text */
}
/* 模态框样式 */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal {
width: 50%;
background-color: #FFFFFF;
border-radius: 10px;
overflow: hidden;
}
/* 设置框标题居左 */
.modal-header {
height: 60px;
background-color: #F1F1F1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
font-size: 18px;
font-weight: bold;
}
.modal-header .close-button {
background: none;
border: none;
font-size: 18px;
cursor: pointer;
}
.modal-body {
padding: 20px;
}
.tabs {
display: flex;
border-bottom: 2px solid #E0E0E0;
margin-bottom: 20px;
}
.tab {
padding: 10px 20px;
cursor: pointer;
margin-right: 10px;
font-weight: 600;
}
/* 悬停时背景色变化但下划线无圆角 */
.tab:hover {
background-color: #F3F4F6;
border-top-left-radius: 8px; /* 左上角圆角 */
border-top-right-radius: 8px; /* 右上角圆角 */
border-bottom-left-radius: 0; /* 左下角无圆角 */
border-bottom-right-radius: 0; /* 右上角无圆角 */
}
.tab.active {
border-bottom: 2px solid #4B5563;
}
.modal-body .tab-content {
display: none;
}
.modal-body .tab-content.active {
display: block;
}
.modal-footer {
display: flex;
justify-content: flex-end;
padding: 10px 20px;
background-color: #F1F1F1;
}
/* 确定按钮背景改为深色 */
.modal-footer button {
padding: 8px 15px;
background-color: #262E45; /* 新背景色 */
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
/* 鼠标悬停确定按钮的样式 */
.modal-footer button:hover {
background-color: #3B4563; /* 保留原悬停效果 */
}
/* 渐隐文字样式 */
.fade-text {
position: fixed;
top: 2%;
left: 50%;
transform: translateX(-50%);
color: #333;
font-size: 16px;
font-weight: bold;
animation: fadeOut 1s forwards;
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
/* 登录模态框样式 */
.login-modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #FFFFFF;
padding: 20px;
border-radius: 10px; /* 与其它模态框一致 */
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 1000;
}
.login-form {
display: flex;
flex-direction: column;
gap: 15px;
}
.login-input {
padding: 8px;
border: 1px solid #E0E0E0;
border-radius: 4px;
}
.login-button {
padding: 8px;
background-color: #262E45;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.login-button:hover {
background-color: #3B4563;
}
/* 注销按钮样式 */
.logout-button {
padding: 5px 10px;
background-color: #E0E0E0;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
.logout-button:hover {
background-color: #D1D5DB;
}
/* 个人信息模态框 */
#profileModal {
display: none;
}
</style>
</head>
<body>
<div class="sidebar">
<div class="logo">
<img src="v38_8.png" alt="Logo">
</div>
<div class="nav-buttons">
<button class="nav-button active" data-title="仪表板" data-icon="mdi:barometer">
<iconify-icon icon="mdi:barometer"></iconify-icon>仪表板
</button>
<button class="nav-button" data-title="电机" data-icon="mdi:motor-outline">
<iconify-icon icon="mdi:motor-outline"></iconify-icon>电机
</button>
<button class="nav-button" data-title="减速机" data-icon="fa6-solid:gears">
<iconify-icon icon="fa6-solid:gears"></iconify-icon>减速机
</button>
<button class="nav-button" data-title="联轴器" data-icon="ri:coupon-4-line">
<iconify-icon icon="ri:coupon-4-line"></iconify-icon>联轴器
</button>
<button class="nav-button" data-title="滚珠丝杆" data-icon="mdi:screw-machine-round-top">
<iconify-icon icon="mdi:screw-machine-round-top"></iconify-icon>滚珠丝杆
</button>
<button class="nav-button" data-title="直线导轨" data-icon="ic:baseline-drag-handle">
<iconify-icon icon="ic:baseline-drag-handle"></iconify-icon>直线导轨
</button>
<button class="nav-button" data-title="轴承" data-icon="ic:baseline-adjust">
<iconify-icon icon="ic:baseline-adjust"></iconify-icon>轴承
</button>
</div>
<div class="user-info">
<!-- 用户头像或登录/注册文字 -->
<div class="user-avatar">
<iconify-icon icon="mdi:barometer"></iconify-icon>
</div>
<div class="user-name"></div>
</div>
</div>
<div class="main-content">
<div class="header">
<div class="header-title">
<!-- 初始状态不会有图标 -->
</div>
<button class="settings-button" id="settingsButton">
<iconify-icon icon="uiw:setting-o"></iconify-icon><span>设置</span>
</button>
</div>
<div class="content-area">
<div class="function-zone">
<h2>功能区域</h2>
<p>Hello 星程技术</p>
</div>
</div>
<div class="status-bar">
网络状态: 在线 | 系统版本: V1.0.0 | 开发者: 星程技术
</div>
</div>
<!-- 模态框 -->
<div class="modal-overlay" id="modalOverlay">
<div class="modal">
<div class="modal-header">
设置
<button class="close-button" id="closeModal">X</button>
</div>
<div class="modal-body">
<div class="tabs">
<div class="tab active">常规设置</div>
<div class="tab">系统设置</div>
<div class="tab">高级设置</div>
</div>
<div class="tab-content active">
<h3>常规设置内容</h3>
<p>这里是常规设置项。</p>
</div>
<div class="tab-content">
<h3>系统设置内容</h3>
<p>这里是系统设置项。</p>
</div>
<div class="tab-content">
<h3>高级设置内容</h3>
<p>这里是高级设置项。</p>
</div>
</div>
<div class="modal-footer">
<button id="confirmButton">确定</button>
</div>
</div>
</div>
<!-- 登录模态框 -->
<div class="modal-overlay login-modal" id="loginModalOverlay">
<div class="modal">
<div class="modal-header">
登录
<button class="close-button">X</button>
</div>
<div class="modal-body">
<form class="login-form">
<input type="text" class="login-input" placeholder="用户名">
<input type="password" class="login-input" placeholder="密码">
<button type="submit" class="login-button">登录</button>
</form>
</div>
<div class="modal-footer">
<!-- 确定按钮 -->
</div>
</div>
</div>
<!-- 个人信息模态框 -->
<div class="modal-overlay" id="profileModalOverlay">
<div class="modal">
<div class="modal-header">
个人信息
<button class="close-button" id="closeProfile">X</button>
</div>
<div class="modal-body">
<div class="user-profile">
<div class="profile-info">
<p>用户名: admin</p>
<!-- 可以添加更多用户信息 -->
</div>
</div>
</div>
<div class="modal-footer">
<button class="logout-button">注销</button>
</div>
</div>
</div>
<script>
const navButtons = document.querySelectorAll('.nav-button');
const headerTitle = document.querySelector('.header-title');
const functionZone = document.querySelector('.function-zone h2');
const settingsButton = document.getElementById('settingsButton');
const modalOverlay = document.getElementById('modalOverlay');
const loginModalOverlay = document.getElementById('loginModalOverlay');
const profileModalOverlay = document.getElementById('profileModalOverlay');
const closeModal = document.getElementById('closeModal');
const closeProfileModal = document.getElementById('closeProfile');
const userInfo = document.querySelector('.user-info');
const userAvatar = document.querySelector('.user-avatar');
const logoutButton = document.querySelector('.logout-button');
const loginRegisterText = document.querySelector('.login-register');
// 默认显示第一个功能页
window.onload = () => {
const defaultButton = document.querySelector('.nav-button.active');
if (defaultButton) {
updateContent(defaultButton);
}
// 检查用户登录状态
checkLoginStatus();
};
// 切换导航功能
navButtons.forEach(button => {
button.addEventListener('click', () => {
navButtons.forEach(b => b.classList.remove('active'));
button.classList.add('active');
updateContent(button);
});
});
function updateContent(button) {
const title = button.getAttribute('data-title');
const icon = button.getAttribute('data-icon');
// 更新顶部标题
headerTitle.innerHTML = `<iconify-icon icon="${icon}"></iconify-icon> ${title}`;
// 更新功能区内容
functionZone.textContent = `欢迎来到 ${title} 页面!`;
// 控制“设置”按钮显示状态
if (title === "仪表板") {
settingsButton.style.display = "flex";
} else {
settingsButton.style.display = "none";
}
}
// 打开设置弹窗
settingsButton.addEventListener('click', () => {
modalOverlay.style.display = 'flex';
});
// 关闭设置弹窗
closeModal.addEventListener('click', () => {
modalOverlay.style.display = 'none';
});
// 打开登录模态框
userAvatar.addEventListener('click', function() {
const isLoggedIn = localStorage.getItem('isLoggedIn');
if (isLoggedIn !== 'true') {
loginModalOverlay.style.display = 'flex';
} else {
profileModalOverlay.style.display = 'flex';
}
});
// 关闭个人信息模态框
closeProfileModal.addEventListener('click', () => {
profileModalOverlay.style.display = 'none';
});
// 处理注销
logoutButton.addEventListener('click', () => {
localStorage.removeItem('isLoggedIn');
profileModalOverlay.style.display = 'none';
window.location.reload();
});
// 登录表单提交处理
document.querySelector('.login-form').addEventListener('submit', function(e) {
e.preventDefault();
const username = this.querySelector('input[type="text"]').value;
const password = this.querySelector('input[type="password"]').value;
// 测试账号信息(admin/123)
if (username === 'admin' && password === '123') {
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('userName', username);
loginModalOverlay.style.display = 'none';
checkLoginStatus();
} else {
alert('用户名或密码错误');
}
});
// 检查用户登录状态
function checkLoginStatus() {
const isLoggedIn = localStorage.getItem('isLoggedIn');
if (isLoggedIn === 'true') {
// 显示用户信息
const userName = localStorage.getItem('userName') || 'admin';
userAvatar.innerHTML = `
<iconify-icon icon="mdi:barometer" style="font-size: 24px;"></iconify-icon>
`;
document.querySelector('.user-name').textContent = userName;
loginRegisterText.style.display = 'none';
} else {
// 显示登录/注册
userAvatar.innerHTML = `
<span role="img" aria-label="登 录/注册">👋</span>
`;
document.querySelector('.user-name').textContent = '登录/注册';
loginRegisterText.style.display = 'block';
}
}
// 模态框TAB切换功能
const modalTabs = document.querySelectorAll('.tab');
const modalBodies = document.querySelectorAll('.tab-content');
modalTabs.forEach((tab, index) => {
tab.addEventListener('click', () => {
modalTabs.forEach(t => t.classList.remove('active'));
modalBodies.forEach(body => body.classList.remove('active'));
tab.classList.add('active');
modalBodies[index].classList.add('active');
});
});
// 确定按钮逻辑
const confirmButton = document.getElementById('confirmButton');
confirmButton.addEventListener('click', () => {
modalOverlay.style.display = 'none'; // 关闭模态框
// 显示“设置已保存”文字
const fadeText = document.createElement('div');
fadeText.className = 'fade-text';
fadeText.textContent = '设置已保存';
document.body.appendChild(fadeText);
// 3秒后移除文字
setTimeout(() => {
fadeText.remove();
}, 3000);
});
// 处理用户头像的悬停效果
userAvatar.addEventListener('mouseover', function() {
this.style.backgroundColor = '#F3F4F6';
});
userAvatar.addEventListener('mouseout', function() {
this.style.backgroundColor = '';
});
// 关闭登录模态框
document.querySelector('.login-modal .close-button').addEventListener('click', () => {
loginModalOverlay.style.display = 'none';
});
// 关闭个人信息模态框
document.querySelector('#profileModalOverlay .close-button').addEventListener('click', () => {
profileModalOverlay.style.display = 'none';
});
</script>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
查看所有已创建的虚拟环境:conda env list
进入(激活)指定环境:conda activate 环境名
退出当前环境:conda deactivate
创建新环境:conda create --name 环境名 python=版本号
删除环境:conda remove --name 环境名 --all
+6
View File
@@ -0,0 +1,6 @@
安装django:pip install django
显示帮助:django-admin --help
创建新项目:django-admin startproject 项目名称
显示启动项目帮助:python manage.py --help
启动项目:python manage.py runserver 端口号
创建项目后应用数据库迁移:python manage.py migrate
+2
View File
@@ -0,0 +1,2 @@
设置 Git 提交的用户名:git config --global user.name "你的用户名"
设置 Git 提交的邮箱地址:git config --global user.email "你的邮箱地址"
+3 -3
View File
@@ -208,8 +208,8 @@ If you develop a new program, and you want it to be of the greatest possible use
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
001-Study Python-Project
Copyright (C) 2025 XCSERVER Copyright (C) 2024 XC-Project
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
@@ -221,7 +221,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
001-Study Copyright (C) 2025 XCSERVER Python-Project Copyright (C) 2024 XC-Project
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
+7
View File
@@ -0,0 +1,7 @@
1、翻译插件
translation
2、网页预览
live edit
3、AI辅助
通义灵码
4、
+42 -1
View File
@@ -1,3 +1,44 @@
# 001-Study # 001-Study
代码学习 学习用仓库
项目结构(前后端分离Django+HTML+CSS+JavaScript):
我们的项目采用了**前后端分离架构**,即前端和后端在开发和部署时是完全独立的。在使用Django作为后端,HTML、CSS、JavaScript作为前端的项目中,合理的项目结构可以帮助你更好地管理代码,保护后端逻辑,并方便后续的功能扩展。以下是一个推荐的项目结构和配置步骤:
```
my_project/ # 项目根目录
│
├── backend/ # 后端目录
│ ├── manage.py # Django管理脚本
│ ├── my_project/ # Django项目配置目录
│ │ ├── __init__.py
│ │ ├── settings.py # Django设置文件
│ │ ├── urls.py # URL路由配置
│ │ ├── wsgi.py # WSGI入口
│ │ └── asgi.py # ASGI入口
│ ├── app1/ # 功能模块1的Django应用
│ │ ├── migrations/ # 数据库迁移文件
│ │ ├── __init__.py
│ │ ├── admin.py # 管理员界面配置
│ │ ├── apps.py # 应用配置
│ │ ├── models.py # 数据模型
│ │ ├── tests.py # 测试文件
│ │ ├── views.py # 视图逻辑
│ │ └── urls.py # 应用的URL配置
│ └── app2/ # 功能模块2的Django应用
│ ├── ... # 同上
│
├── frontend/ # 前端目录
│ ├── app1/ # 功能模块1的前端
│ │ ├── index.html # HTML文件
│ │ ├── style.css # CSS文件
│ │ └── script.js # JavaScript文件
│ └── app2/ # 功能模块2的前端
│ ├── ... # 同上
│
└── static/ # 静态文件目录
├── css/ # 全局CSS文件
├── js/ # 全局JavaScript文件
└── images/ # 图片资源
```