Фаза 1: мастер первого запуска — SettingsStore, GitManager (auto-init+коммиты), SyncManager (проверка соединений+ErrorCatalog), WelcomeWizard/ProviderSetupGuide; тесты smoke/git/vault (12/12)

This commit is contained in:
Flora (opencode)
2026-08-17 00:43:33 +03:00
parent 980fbcedcb
commit ed633ae036
18 changed files with 1412 additions and 29 deletions
+63 -6
View File
@@ -3,7 +3,7 @@ import QtQuick.Controls
import QtQuick.Layouts
// Главное окно: меню вверху, три панели (дерево / редактор / правая).
// Фаза 0: каркас. Содержимое панелей наполняется в следующих фазах.
// Фазы 0-1: каркас + мастер первого запуска. Контент панелей — в следующих фазах.
ApplicationWindow {
id: window
width: 1280
@@ -12,10 +12,27 @@ ApplicationWindow {
title: "Flora"
color: "white"
// Мастер первого запуска: показываем, если ещё нет ни одного хранилища.
WelcomeWizard {
id: welcomeWizard
firstRun: vaultManager.vaults.length === 0
onFinished: vaultSwitcher.close()
}
Component.onCompleted: {
if (vaultManager.vaults.length === 0)
welcomeWizard.open()
}
function openWizard() {
welcomeWizard.firstRun = false
welcomeWizard.open()
}
menuBar: MenuBar {
Menu {
title: qsTr("&Файл")
Action { text: qsTr("Открыть хранилище…"); onTriggered: vaultSwitcher.open() }
Action { text: qsTr("Добавить хранилище…"); onTriggered: window.openWizard() }
Menu {
title: qsTr("Экспорт")
Action { text: qsTr("В HTML…"); enabled: false }
@@ -60,20 +77,60 @@ ApplicationWindow {
}
}
// Переключатель хранилищ (кнопка внизу слева, в FileTreePanel)
Popup {
id: vaultSwitcher
x: 12
y: window.height - height - 12
width: 280
width: 320
modal: false
closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
ColumnLayout {
width: parent.width
Label { text: qsTr("Хранилища (Фаза 2)") }
Button { text: qsTr("Это окно: %1").arg(vaultManager.currentVault) }
spacing: 6
Label {
text: qsTr("Хранилища")
font.bold: true
}
ListView {
id: vaultList
Layout.preferredHeight: Math.min(200, contentHeight)
Layout.fillWidth: true
model: vaultManager.vaults
clip: true
delegate: ItemDelegate {
width: ListView.view.width
text: modelData
highlighted: modelData === vaultManager.currentVault
onClicked: {
if (modelData !== vaultManager.currentVault) {
vaultManager.selectVault(modelData)
}
}
}
}
Label {
visible: vaultList.count === 0
text: qsTr("Хранилищ пока нет")
color: "#888"
}
Label {
text: qsTr("Текущее: %1").arg(vaultManager.currentVault.length > 0
? vaultManager.currentVault : "—")
color: "#666"
elide: Text.ElideMiddle
Layout.fillWidth: true
}
Button {
Layout.fillWidth: true
text: qsTr("Добавить новое хранилище…")
onClicked: { vaultSwitcher.close(); vaultManager.setCurrentVault("/") }
onClicked: { vaultSwitcher.close(); window.openWizard() }
}
}
}
+184
View File
@@ -0,0 +1,184 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// Диалог настройки провайдера синхронизации с пошаговой инструкцией,
// проверкой соединения и каталогом ошибок (ErrorCatalog в SyncManager).
Dialog {
id: root
property int providerIndex: -1
property string providerName: ""
property bool connected: false
signal saved(int index)
readonly property bool isGit: providerIndex <= 2
title: qsTr("Подключение: %1").arg(providerName)
modal: true
width: 640
height: 520
anchors.centerIn: parent
closePolicy: Dialog.NoAutoClose
function defaultUrl() {
switch (root.providerIndex) {
case 0: return "https://github.com"
case 1: return "https://gitlab.com"
case 2: return "http://localhost:3000"
case 3: return "https://nextcloud.local/remote.php/dav/files/USER"
default: return "http://127.0.0.1:8384"
}
}
function tokenName() {
switch (root.providerIndex) {
case 0: return qsTr("Токен GitHub (Personal Access Token)")
case 1: return qsTr("Токен GitLab (PRIVATE-TOKEN)")
case 2: return qsTr("Токен Gitea (Personal Access Token)")
case 3: return qsTr("Пароль от Nextcloud")
default: return qsTr("API-ключ Syncthing")
}
}
Component.onCompleted: { urlField.text = defaultUrl() }
ColumnLayout {
anchors.fill: parent
spacing: 10
// Инструкция
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: 150
color: "#f4f6fa"
radius: 6
Flickable {
anchors.fill: parent
anchors.margins: 8
ScrollBar.vertical: ScrollBar {}
clip: true
contentWidth: width
contentHeight: instText.implicitHeight
Text {
id: instText
width: parent.width
wrapMode: Text.Wrap
textFormat: Text.MarkdownText
color: "#333"
text: root.providerIndex === 0
? "**Как подключить GitHub:**\n\n"
+ "1. Создайте токен: [github.com/settings/tokens](https://github.com/settings/tokens) — scope **repo** (классический) или Fine-grained с правом **Contents: Read and write**.\n"
+ "2. Создайте **пустой** репозиторий (без README/.gitignore — иначе конфликт истории): New repository.\n"
+ "3. Вставьте токен ниже и нажмите «Проверить».\n"
+ "4. Альтернатива — SSH-ключ (Подключение → SSH, доступно в Фазе 11)."
: root.providerIndex === 1
? "**Как подключить GitLab:**\n\n"
+ "1. Токен: Настройки → Access Tokens — scope **api** (или **read_repository** + **write_repository**).\n"
+ "2. Создайте **пустой** репозиторий в своём аккаунте/группе.\n"
+ "3. Для self-hosted: укажите адрес инстанса, например http://gitlab.local. Вставьте токен и нажмите «Проверить».\n"
+ "4. Альтернатива — SSH-ключ (доступно в Фазе 11)."
: root.providerIndex === 2
? "**Как подключить Gitea:**\n\n"
+ "1. Токен: Настройки аккаунта → Приложения → **Создать новый токен** (scope **repo**).\n"
+ "2. Создайте **пустой** репозиторий на своём инстансе.\n"
+ "3. Укажите адрес инстанса (например http://localhost:3000), вставьте токен и нажмите «Проверить».\n"
+ "4. Альтернатива — SSH-ключ (доступно в Фазе 11)."
: root.providerIndex === 3
? "**Как подключить Nextcloud (WebDAV):**\n\n"
+ "1. Откройте приложение Files, создайте папку для синхронизации (например **Flora**).\n"
+ "2. Адрес WebDAV: https://ВАШ_ХОСТ/remote.php/dav/files/ВАШ_ЛОГИН/\n"
+ "3. Укажите логин и пароль аккаунта Nextcloud и нажмите «Проверить».\n"
+ "4. Рекомендуется создать пароль приложения в Настройках → Безопасность."
: "**Как подключить Syncthing:**\n\n"
+ "1. Установите и запустите Syncthing на этом устройстве.\n"
+ "2. API-ключ: Действия → Настройки → Показывать расширенное → API-ключ.\n"
+ "3. Адрес API по умолчанию: http://127.0.0.1:8384. Вставьте ключ и нажмите «Проверить».\n"
+ "4. Затем добавьте папку хранилища в Syncthing как обычную папку."
}
}
}
// Поля
ColumnLayout {
Layout.fillWidth: true
spacing: 6
Label { text: qsTr("Адрес сервера") }
TextField { id: urlField; Layout.fillWidth: true }
Label {
visible: root.providerIndex === 3
text: qsTr("Логин (для WebDAV):")
}
TextField {
id: userField
Layout.fillWidth: true
visible: root.providerIndex === 3
placeholderText: qsTr("Логин Nextcloud")
}
Label { text: tokenName() }
TextField {
id: tokenField
Layout.fillWidth: true
echoMode: TextInput.Password
placeholderText: qsTr("Вставьте значение")
}
}
// Результат / ошибка
Label {
id: resultLabel
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: text.length > 0
color: root.connected ? "green" : "#b00020"
}
Item { Layout.fillHeight: true }
RowLayout {
Layout.fillWidth: true
Button {
text: qsTr("Отмена")
onClicked: root.reject()
}
Item { Layout.fillWidth: true }
Button {
text: qsTr("Проверить соединение")
enabled: tokenField.text.length > 0 && !syncManager.busy
onClicked: {
resultLabel.text = ""
root.connected = false
syncManager.testConnection(root.providerIndex,
urlField.text, userField.text,
tokenField.text)
}
}
Button {
text: qsTr("Сохранить")
enabled: root.connected
onClicked: {
settingsStore.addProvider(root.providerName, {
url: urlField.text,
user: userField.text,
token: tokenField.text,
})
root.saved(root.providerIndex)
root.accept()
}
}
}
}
Connections {
target: syncManager
function onConnectionResult(provider, ok, code, title, hint, raw) {
if (provider !== root.providerIndex)
return
root.connected = ok
resultLabel.text = ok
? qsTr("Соединение установлено. Нажмите «Сохранить».")
: title + (hint && hint.length > 0 ? "\n" + hint : "")
}
}
}
+164
View File
@@ -0,0 +1,164 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
// Мастер первого запуска / добавления хранилища:
// 1) выбор папки (новая или с файлами);
// 2) автосоздание git-репозитория + подключение провайдеров (опционально);
// 3) готово.
Dialog {
id: root
required property bool firstRun
readonly property int stepFolder: 0
readonly property int stepSetup: 1
property int step: stepFolder
property string vaultPath: ""
property string setupStatus: ""
signal finished()
title: firstRun ? qsTr("Первое знакомство: создайте хранилище")
: qsTr("Новое хранилище")
modal: true
width: 560
height: 480
anchors.centerIn: parent
closePolicy: Dialog.NoAutoClose
StackLayout {
id: stack
anchors.fill: parent
currentIndex: root.step
// ---------- Шаг 1: выбор папки ----------
ColumnLayout {
spacing: 12
Label {
text: qsTr("Выберите локальную папку — это будет ваше хранилище.\n"
+ "Можно указать новую папку (будет создана) или уже существующую с файлами.")
wrapMode: Text.Wrap
Layout.fillWidth: true
}
RowLayout {
Layout.fillWidth: true
TextField {
id: pathField
Layout.fillWidth: true
placeholderText: qsTr("Путь к папке…")
text: root.vaultPath
onTextChanged: root.vaultPath = text
}
Button {
text: qsTr("Обзор…")
onClicked: folderDialog.open()
}
}
FolderDialog {
id: folderDialog
title: qsTr("Выберите папку хранилища")
onAccepted: root.vaultPath = selectedFolder.localFile ?? ""
}
Label {
id: step1Error
color: "red"
wrapMode: Text.Wrap
Layout.fillWidth: true
text: ""
}
Item { Layout.fillHeight: true }
RowLayout {
Layout.fillWidth: true
Item { Layout.fillWidth: true }
Button {
text: qsTr("Отмена")
onClicked: root.reject()
}
Button {
text: qsTr("Далее")
enabled: root.vaultPath.length > 0 && !busyOverlay.running
onClicked: {
step1Error.text = ""
busyOverlay.running = true
const err = vaultManager.createVault(root.vaultPath)
busyOverlay.running = false
if (err.length > 0) {
step1Error.text = err
return
}
root.step = stepSetup
}
}
}
}
// ---------- Шаг 2: git + провайдеры ----------
ColumnLayout {
spacing: 12
Label {
text: qsTr("Хранилище готово. Внутри автоматически создан git-репозиторий.\n"
+ "При желании подключите синхронизацию:")
wrapMode: Text.Wrap
Layout.fillWidth: true
}
GridLayout {
columns: 2
Layout.fillWidth: true
Layout.fillHeight: true
columnSpacing: 8
rowSpacing: 8
Button { text: "GitHub"; Layout.fillWidth: true; onClicked: openProviderGuide(0, "GitHub") }
Button { text: "GitLab"; Layout.fillWidth: true; onClicked: openProviderGuide(1, "GitLab") }
Button { text: "Gitea"; Layout.fillWidth: true; onClicked: openProviderGuide(2, "Gitea") }
Button { text: "Nextcloud (WebDAV)"; Layout.fillWidth: true; onClicked: openProviderGuide(3, "Nextcloud (WebDAV)") }
Button { text: "Syncthing"; Layout.fillWidth: true; onClicked: openProviderGuide(4, "Syncthing") }
function openProviderGuide(idx, name) {
providerGuideForButtons.providerIndex = idx
providerGuideForButtons.providerName = name
providerGuideForButtons.connected = false
providerGuideForButtons.open()
}
Label {
color: "#888"
Layout.columnSpan: 2
}
}
RowLayout {
Layout.fillWidth: true
Item { Layout.fillWidth: true }
Button {
text: qsTr("Готово")
onClicked: {
vaultManager.selectVault(root.vaultPath)
root.accept()
root.finished()
}
}
}
}
}
BusyIndicator {
id: busyOverlay
anchors.centerIn: parent
running: false
visible: running
}
ProviderSetupGuide {
id: providerGuideForButtons
}
onRejected: {
if (firstRun) {
// Пусть пользователь продолжит позже; хранилище не выбрано.
Qt.callLater(() => { console.log("Мастер отменён") })
visible = false
}
}
}