diff --git a/Docs/README.es.md b/Docs/README.es.md index 5debe64..e0416f0 100644 --- a/Docs/README.es.md +++ b/Docs/README.es.md @@ -1,6 +1,6 @@ # SmartAsyncImage -Un `AsyncImage` para SwiftUI (iOS) mas inteligente y rapido, con cache en memoria y en disco, cancelacion y concurrencia de Swift 6. +Un `AsyncImage` para SwiftUI (iOS) más inteligente y rápido, con caché en memoria y en disco, cancelación y concurrencia de Swift 6. [![CI](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml) [![Coverage](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage/branch/main/graph/badge.svg)](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage) @@ -12,34 +12,34 @@ Un `AsyncImage` para SwiftUI (iOS) mas inteligente y rapido, con cache en memori ![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) [![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) -> **Idioma** · [English](../README.md) · Español · [Português (Brasil)](README.pt-BR.md) · [日本語](README.ja.md) +> 🌍 **Idioma** · [English](../README.md) · Español · [Português (Brasil)](README.pt-BR.md) · [日本語](README.ja.md) · [简体中文](README.zh-CN.md) · [한국어](README.ko.md) · [Русский](README.ru.md) -## Caracteristicas +## Características - API compatible con SwiftUI con un view model observable - Manejo inteligente de fases: `empty`, `loading`, `success(Image)`, `failure(Error)` -- Protocolo de cache en memoria con implementaciones intercambiables -- Cache en disco para persistencia entre ejecuciones -- Concurrencia de Swift (`async/await`) con cancelacion cooperativa +- Protocolo de caché en memoria con implementaciones intercambiables +- Caché en disco para persistencia entre ejecuciones +- Concurrencia de Swift (`async/await`) con cancelación cooperativa - Actualizaciones de estado seguras en MainActor -💬 **[Participa en la discusion. Comentarios y preguntas son bienvenidos](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** +💬 **[Participa en la discusión. Comentarios y preguntas son bienvenidos](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** ## Requisitos - iOS 17+ - Swift 6.1+ - Swift Package Manager -## 📦 Instalacion (Swift Package Manager) +## 📦 Instalación (Swift Package Manager) -### Via Xcode +### Vía Xcode 1. Abre tu proyecto en Xcode 2. Ve a **File → Add Packages...** 3. Ingresa la URL del repositorio: `https://github.com/gentle-giraffe-apps/SmartAsyncImage.git` -4. Elige una regla de version (o `main` durante el desarrollo) +4. Elige una regla de versión (o `main` durante el desarrollo) 5. Agrega el producto **SmartAsyncImage** a tu target de la app -### Via `Package.swift` +### Vía `Package.swift` ```swift dependencies: [ @@ -49,32 +49,32 @@ dependencies: [ Luego agrega `"SmartAsyncImage"` a las `dependencies` de tu target. -## App de Demostracion +## App de Demostración -Se incluye una app de demostracion en SwiftUI en este repositorio usando una referencia local al paquete. +Se incluye una app de demostración en SwiftUI en este repositorio usando una referencia local al paquete. **Ruta:** ``` Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj ``` -### Como Ejecutar +### Cómo Ejecutar 1. Clona el repositorio: ```bash git clone https://github.com/gentle-giraffe-apps/SmartAsyncImage.git ``` -2. Abre el proyecto de demostracion: +2. Abre el proyecto de demostración: ``` Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj ``` 3. Selecciona un simulador con iOS 17+. 4. Compila y ejecuta (⌘R). -El proyecto esta preconfigurado con una referencia local de Swift Package a `SmartAsyncImage` y deberia ejecutarse sin configuracion adicional. +El proyecto está preconfigurado con una referencia local de Swift Package a `SmartAsyncImage` y debería ejecutarse sin configuración adicional. ## Uso -### Ejemplo Rapido (SwiftUI) +### Ejemplo Rápido (SwiftUI) ```swift import SwiftUI import SmartAsyncImage @@ -108,23 +108,23 @@ struct MinimalRemoteImageView: View { ## Calidad y Herramientas -Este proyecto aplica controles de calidad mediante CI y analisis estatico: +Este proyecto aplica controles de calidad mediante CI y análisis estático: - **CI:** Todos los commits a `main` deben pasar las verificaciones de GitHub Actions -- **Analisis estatico:** DeepSource se ejecuta en cada commit a `main`. - La insignia indica el numero actual de problemas pendientes de analisis estatico. -- **Cobertura de tests:** Codecov reporta la cobertura de lineas para la rama `main` +- **Análisis estático:** DeepSource se ejecuta en cada commit a `main`. + La insignia indica el número actual de problemas pendientes de análisis estático. +- **Cobertura de tests:** Codecov reporta la cobertura de líneas para la rama `main` Captura de Codecov
Captura de cobertura de codigo por archivo y modulo (grafico de arbol de Codecov) -Estas verificaciones tienen como objetivo mantener el sistema de diseno seguro para evolucionar con el tiempo. +Estas verificaciones tienen como objetivo mantener el sistema de diseño seguro para evolucionar con el tiempo. --- @@ -145,7 +145,7 @@ flowchart TD ## 🤖 Nota sobre Herramientas -Partes de la redaccion y el refinamiento editorial en este repositorio fueron aceleradas utilizando modelos de lenguaje grandes (incluyendo ChatGPT, Claude y Gemini) bajo diseno, validacion y aprobacion final humana directa. Todas las decisiones tecnicas, el codigo y las conclusiones arquitectonicas son de autoria y verificacion del mantenedor del repositorio. +Partes de la redacción y el refinamiento editorial en este repositorio fueron aceleradas utilizando modelos de lenguaje grandes (incluyendo ChatGPT, Claude y Gemini) bajo diseño, validación y aprobación final humana directa. Todas las decisiones técnicas, el código y las conclusiones arquitectónicas son de autoría y verificación del mantenedor del repositorio. --- diff --git a/Docs/README.ja.md b/Docs/README.ja.md index a5f1fe8..f7dc21f 100644 --- a/Docs/README.ja.md +++ b/Docs/README.ja.md @@ -12,7 +12,7 @@ SwiftUI (iOS) 向けの、より高速でスマートな `AsyncImage`。メモ ![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) [![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) -> **言語** · [English](../README.md) · [Español](README.es.md) · [Português (Brasil)](README.pt-BR.md) · 日本語 +> 🌍 **言語** · [English](../README.md) · [Español](README.es.md) · [Português (Brasil)](README.pt-BR.md) · 日本語 · [简体中文](README.zh-CN.md) · [한국어](README.ko.md) · [Русский](README.ru.md) ## 特徴 - Observable なビューモデルを備えた SwiftUI 対応 API diff --git a/Docs/README.ko.md b/Docs/README.ko.md new file mode 100644 index 0000000..aa24267 --- /dev/null +++ b/Docs/README.ko.md @@ -0,0 +1,165 @@ +# SmartAsyncImage + +SwiftUI (iOS)를 위한 더 스마트하고 빠른 `AsyncImage` 대체제. 메모리 및 디스크 캐싱, 취소, Swift 6 동시성을 기본 지원합니다. + +[![CI](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml) +[![Coverage](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage/branch/main/graph/badge.svg)](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage) +[![Swift](https://img.shields.io/badge/Swift-6.1+-orange.svg)](https://swift.org) +![Bazel](https://img.shields.io/badge/Bazel-enabled-555?logo=bazel) +[![SPM Compatible](https://img.shields.io/badge/SPM-Compatible-brightgreen.svg)](https://swift.org/package-manager/) +[![Platforms](https://img.shields.io/badge/platforms-iOS%2017%2B-blue)](https://developer.apple.com/ios/) +![Commit activity](https://img.shields.io/github/commit-activity/y/gentle-giraffe-apps/SmartAsyncImage) +![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) +[![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) + +> 🌍 **언어** · [English](../README.md) · [Español](README.es.md) · [Português (Brasil)](README.pt-BR.md) · [日本語](README.ja.md) · [简体中文](README.zh-CN.md) · 한국어 · [Русский](README.ru.md) + +## 특징 +- Observable 뷰 모델을 갖춘 SwiftUI 친화적 API +- 스마트한 단계 관리: `empty`, `loading`, `success(Image)`, `failure(Error)` +- 플러그인 가능한 구현을 지원하는 메모리 캐시 프로토콜 +- 앱 재시작 간 데이터를 유지하는 디스크 캐시 +- Swift Concurrency (`async/await`) 및 협력적 취소 +- MainActor 안전한 상태 업데이트 + +💬 **[토론에 참여하세요. 피드백과 질문을 환영합니다](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** + +## 요구 사항 +- iOS 17+ +- Swift 6.1+ +- Swift Package Manager + +## 📦 설치 (Swift Package Manager) + +### Xcode를 통한 설치 + +1. Xcode에서 프로젝트를 엽니다 +2. **File → Add Packages...** 로 이동합니다 +3. 저장소 URL을 입력합니다: `https://github.com/gentle-giraffe-apps/SmartAsyncImage.git` +4. 버전 규칙을 선택합니다 (개발 중에는 `main` 선택 가능) +5. **SmartAsyncImage** 제품을 앱 타겟에 추가합니다 + +### `Package.swift`를 통한 설치 + +```swift +dependencies: [ + .package(url: "https://github.com/gentle-giraffe-apps/SmartAsyncImage.git", from: "1.0.0") +] +``` + +그런 다음 타겟의 `dependencies`에 `"SmartAsyncImage"`를 추가합니다. + +## 데모 앱 + +로컬 패키지 참조를 사용하는 SwiftUI 데모 앱이 이 저장소에 포함되어 있습니다. + +**경로:** +``` +Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj +``` + +### 실행 방법 +1. 저장소를 클론합니다: + ```bash + git clone https://github.com/gentle-giraffe-apps/SmartAsyncImage.git + ``` +2. 데모 프로젝트를 엽니다: + ``` + Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj + ``` +3. iOS 17+ 시뮬레이터를 선택합니다. +4. 빌드 및 실행합니다 (⌘R). + +프로젝트는 `SmartAsyncImage`에 대한 로컬 Swift Package 참조로 사전 구성되어 있으며, 추가 설정 없이 실행할 수 있습니다. + +## 사용법 + +### 빠른 예제 (SwiftUI) +```swift +import SwiftUI +import SmartAsyncImage + +struct MinimalRemoteImageView: View { + let imageURL = URL(string: "https://picsum.photos/300") + + var body: some View { + + // 교체 전: AsyncImage(url: imageURL) { phase in + // ------------------------------------------------ + // 교체 후: + + SmartAsyncImage(url: imageURL) { phase in + + // ------------------------------------------------ + + switch phase { + case .empty, .loading: + ProgressView() + case .success(let image): + image.resizable().scaledToFit() + case .failure: + Image(systemName: "photo") + } + } + .frame(width: 150, height: 150) + } +} +``` + +## 품질 및 도구 + +이 프로젝트는 CI와 정적 분석을 통해 품질 관리를 시행합니다: + +- **CI:** `main`에 대한 모든 커밋은 GitHub Actions 검사를 통과해야 합니다 +- **정적 분석:** DeepSource가 `main`에 대한 모든 커밋에서 실행됩니다. + 배지는 현재 미해결 정적 분석 이슈 수를 나타냅니다. +- **테스트 커버리지:** Codecov가 `main` 브랜치의 라인 커버리지를 보고합니다 + +Codecov 스냅샷
+ + 파일 및 모듈별 코드 커버리지 스냅샷 (Codecov 트리 그래프) + + +이러한 검사는 설계 시스템이 안전하게 발전할 수 있도록 하기 위한 것입니다. + +--- + +## 아키텍처 + +```mermaid +flowchart TD + SAI["SmartAsyncImage
(SwiftUI View)"] --> VM["SmartAsyncImage
ViewModel"] + VM --> Phase["SmartAsyncImage
Phase"] + VM --> MemProto["SmartAsyncImageMemory
CacheProtocol"] + MemProto --> Mem["SmartAsyncImage
MemoryCache
(actor)"] + Mem --> Disk["SmartAsyncImage
DiskCache"] + Disk --> Encoder["SmartAsyncImage
Encoder"] + Mem --> URLSession[["URLSession"]] +``` + +--- + +## 🤖 도구 참고 사항 + +이 저장소의 초안 작성 및 편집 다듬기 일부는 대규모 언어 모델(ChatGPT, Claude, Gemini 포함)을 활용하여 가속되었으며, 인간의 직접적인 설계, 검증 및 최종 승인 하에 수행되었습니다. 모든 기술적 결정, 코드 및 아키텍처 결론은 저장소 관리자가 작성하고 검증했습니다. + +--- + +## 🔐 라이선스 + +MIT 라이선스 +개인 및 상업적 용도로 자유롭게 사용할 수 있습니다. + +--- + +## 👤 저자 + +**Jonathan Ritchey** 제작 +Gentle Giraffe Apps +시니어 iOS 엔지니어 --- Swift | SwiftUI | Concurrency + +![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fgithub.com%2Fgentle-giraffe-apps%2FSmartAsyncImage) diff --git a/Docs/README.pt-BR.md b/Docs/README.pt-BR.md index 9fafd54..e78c03e 100644 --- a/Docs/README.pt-BR.md +++ b/Docs/README.pt-BR.md @@ -1,6 +1,6 @@ # SmartAsyncImage -Um `AsyncImage` para SwiftUI (iOS) mais inteligente e rapido, com cache em memoria e em disco, cancelamento e concorrencia do Swift 6. +Um `AsyncImage` para SwiftUI (iOS) mais inteligente e rápido, com cache em memória e em disco, cancelamento e concorrência do Swift 6. [![CI](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml) [![Coverage](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage/branch/main/graph/badge.svg)](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage) @@ -12,31 +12,31 @@ Um `AsyncImage` para SwiftUI (iOS) mais inteligente e rapido, com cache em memor ![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) [![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) -> **Idioma** · [English](../README.md) · [Español](README.es.md) · Português (Brasil) · [日本語](README.ja.md) +> 🌍 **Idioma** · [English](../README.md) · [Español](README.es.md) · Português (Brasil) · [日本語](README.ja.md) · [简体中文](README.zh-CN.md) · [한국어](README.ko.md) · [Русский](README.ru.md) ## Funcionalidades -- API compativel com SwiftUI com um view model observavel +- API compatível com SwiftUI com um view model observável - Gerenciamento inteligente de fases: `empty`, `loading`, `success(Image)`, `failure(Error)` -- Protocolo de cache em memoria com implementacoes intercambiaveis -- Cache em disco para persistencia entre execucoes -- Concorrencia do Swift (`async/await`) com cancelamento cooperativo -- Atualizacoes de estado seguras no MainActor +- Protocolo de cache em memória com implementações intercambiáveis +- Cache em disco para persistência entre execuções +- Concorrência do Swift (`async/await`) com cancelamento cooperativo +- Atualizações de estado seguras no MainActor -💬 **[Participe da discussao. Feedback e perguntas sao bem-vindos](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** +💬 **[Participe da discussão. Feedback e perguntas são bem-vindos](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** ## Requisitos - iOS 17+ - Swift 6.1+ - Swift Package Manager -## 📦 Instalacao (Swift Package Manager) +## 📦 Instalação (Swift Package Manager) ### Via Xcode 1. Abra seu projeto no Xcode -2. Va em **File → Add Packages...** -3. Insira a URL do repositorio: `https://github.com/gentle-giraffe-apps/SmartAsyncImage.git` -4. Escolha uma regra de versao (ou `main` durante o desenvolvimento) +2. Vá em **File → Add Packages...** +3. Insira a URL do repositório: `https://github.com/gentle-giraffe-apps/SmartAsyncImage.git` +4. Escolha uma regra de versão (ou `main` durante o desenvolvimento) 5. Adicione o produto **SmartAsyncImage** ao target do seu app ### Via `Package.swift` @@ -47,11 +47,11 @@ dependencies: [ ] ``` -Em seguida, adicione `"SmartAsyncImage"` as `dependencies` do seu target. +Em seguida, adicione `"SmartAsyncImage"` às `dependencies` do seu target. -## App de Demonstracao +## App de Demonstração -Um app de demonstracao em SwiftUI esta incluido neste repositorio usando uma referencia local ao pacote. +Um app de demonstração em SwiftUI está incluído neste repositório usando uma referência local ao pacote. **Caminho:** ``` @@ -59,22 +59,22 @@ Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj ``` ### Como Executar -1. Clone o repositorio: +1. Clone o repositório: ```bash git clone https://github.com/gentle-giraffe-apps/SmartAsyncImage.git ``` -2. Abra o projeto de demonstracao: +2. Abra o projeto de demonstração: ``` Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj ``` 3. Selecione um simulador com iOS 17+. 4. Compile e execute (⌘R). -O projeto ja esta configurado com uma referencia local de Swift Package para `SmartAsyncImage` e deve executar sem configuracao adicional. +O projeto já está configurado com uma referência local de Swift Package para `SmartAsyncImage` e deve executar sem configuração adicional. ## Uso -### Exemplo Rapido (SwiftUI) +### Exemplo Rápido (SwiftUI) ```swift import SwiftUI import SmartAsyncImage @@ -108,11 +108,11 @@ struct MinimalRemoteImageView: View { ## Qualidade e Ferramentas -Este projeto aplica controles de qualidade via CI e analise estatica: +Este projeto aplica controles de qualidade via CI e análise estática: -- **CI:** Todos os commits em `main` devem passar nas verificacoes do GitHub Actions -- **Analise estatica:** O DeepSource e executado em cada commit em `main`. - O badge indica o numero atual de problemas pendentes de analise estatica. +- **CI:** Todos os commits em `main` devem passar nas verificações do GitHub Actions +- **Análise estática:** O DeepSource é executado em cada commit em `main`. + O badge indica o número atual de problemas pendentes de análise estática. - **Cobertura de testes:** O Codecov reporta a cobertura de linhas para a branch `main` Captura do Codecov
@@ -120,11 +120,11 @@ Este projeto aplica controles de qualidade via CI e analise estatica: Captura de cobertura de codigo por arquivo e modulo (grafico de arvore do Codecov) -Essas verificacoes tem como objetivo manter o sistema de design seguro para evoluir ao longo do tempo. +Essas verificações têm como objetivo manter o sistema de design seguro para evoluir ao longo do tempo. --- @@ -145,13 +145,13 @@ flowchart TD ## 🤖 Nota sobre Ferramentas -Partes da redacao e do refinamento editorial neste repositorio foram aceleradas utilizando modelos de linguagem grandes (incluindo ChatGPT, Claude e Gemini) sob design, validacao e aprovacao final humana direta. Todas as decisoes tecnicas, codigo e conclusoes arquiteturais sao de autoria e verificacao do mantenedor do repositorio. +Partes da redação e do refinamento editorial neste repositório foram aceleradas utilizando modelos de linguagem grandes (incluindo ChatGPT, Claude e Gemini) sob design, validação e aprovação final humana direta. Todas as decisões técnicas, código e conclusões arquiteturais são de autoria e verificação do mantenedor do repositório. --- -## 🔐 Licenca +## 🔐 Licença -Licenca MIT +Licença MIT Livre para uso pessoal e comercial. --- diff --git a/Docs/README.ru.md b/Docs/README.ru.md new file mode 100644 index 0000000..7b9f77c --- /dev/null +++ b/Docs/README.ru.md @@ -0,0 +1,165 @@ +# SmartAsyncImage + +Более умная и быстрая замена `AsyncImage` для SwiftUI (iOS) со встроенным кэшированием в памяти и на диске, отменой и поддержкой конкурентности Swift 6. + +[![CI](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml) +[![Coverage](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage/branch/main/graph/badge.svg)](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage) +[![Swift](https://img.shields.io/badge/Swift-6.1+-orange.svg)](https://swift.org) +![Bazel](https://img.shields.io/badge/Bazel-enabled-555?logo=bazel) +[![SPM Compatible](https://img.shields.io/badge/SPM-Compatible-brightgreen.svg)](https://swift.org/package-manager/) +[![Platforms](https://img.shields.io/badge/platforms-iOS%2017%2B-blue)](https://developer.apple.com/ios/) +![Commit activity](https://img.shields.io/github/commit-activity/y/gentle-giraffe-apps/SmartAsyncImage) +![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) +[![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) + +> 🌍 **Язык** · [English](../README.md) · [Español](README.es.md) · [Português (Brasil)](README.pt-BR.md) · [日本語](README.ja.md) · [简体中文](README.zh-CN.md) · [한국어](README.ko.md) · Русский + +## Возможности +- SwiftUI-совместимый API с наблюдаемой моделью представления +- Умное управление фазами: `empty`, `loading`, `success(Image)`, `failure(Error)` +- Протокол кэширования в памяти с подключаемыми реализациями +- Дисковый кэш для сохранения данных между запусками приложения +- Swift Concurrency (`async/await`) с кооперативной отменой +- Безопасное обновление состояния на MainActor + +💬 **[Присоединяйтесь к обсуждению. Обратная связь и вопросы приветствуются](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** + +## Требования +- iOS 17+ +- Swift 6.1+ +- Swift Package Manager + +## 📦 Установка (Swift Package Manager) + +### Через Xcode + +1. Откройте свой проект в Xcode +2. Перейдите в **File → Add Packages...** +3. Введите URL репозитория: `https://github.com/gentle-giraffe-apps/SmartAsyncImage.git` +4. Выберите правило версионирования (или `main` для разработки) +5. Добавьте продукт **SmartAsyncImage** в целевой модуль вашего приложения + +### Через `Package.swift` + +```swift +dependencies: [ + .package(url: "https://github.com/gentle-giraffe-apps/SmartAsyncImage.git", from: "1.0.0") +] +``` + +Затем добавьте `"SmartAsyncImage"` в `dependencies` вашего целевого модуля. + +## Демо-приложение + +В этом репозитории находится демо-приложение на SwiftUI, использующее локальную ссылку на пакет. + +**Путь:** +``` +Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj +``` + +### Как запустить +1. Клонируйте репозиторий: + ```bash + git clone https://github.com/gentle-giraffe-apps/SmartAsyncImage.git + ``` +2. Откройте демо-проект: + ``` + Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj + ``` +3. Выберите симулятор с iOS 17+. +4. Соберите и запустите (⌘R). + +Проект предварительно настроен с локальной ссылкой на Swift Package `SmartAsyncImage` и должен запускаться без дополнительной настройки. + +## Использование + +### Быстрый пример (SwiftUI) +```swift +import SwiftUI +import SmartAsyncImage + +struct MinimalRemoteImageView: View { + let imageURL = URL(string: "https://picsum.photos/300") + + var body: some View { + + // замените: AsyncImage(url: imageURL) { phase in + // ------------------------------------------------ + // на: + + SmartAsyncImage(url: imageURL) { phase in + + // ------------------------------------------------ + + switch phase { + case .empty, .loading: + ProgressView() + case .success(let image): + image.resizable().scaledToFit() + case .failure: + Image(systemName: "photo") + } + } + .frame(width: 150, height: 150) + } +} +``` + +## Качество и инструменты + +Этот проект обеспечивает контроль качества через CI и статический анализ: + +- **CI:** Все коммиты в `main` должны проходить проверки GitHub Actions +- **Статический анализ:** DeepSource запускается при каждом коммите в `main`. + Значок показывает текущее количество нерешённых проблем статического анализа. +- **Покрытие тестами:** Codecov отчитывается о покрытии строк для ветки `main` + +Снимок Codecov
+ + Снимок покрытия кода по файлам и модулям (древовидный график Codecov) + + +Эти проверки предназначены для того, чтобы дизайн-система могла безопасно развиваться со временем. + +--- + +## Архитектура + +```mermaid +flowchart TD + SAI["SmartAsyncImage
(SwiftUI View)"] --> VM["SmartAsyncImage
ViewModel"] + VM --> Phase["SmartAsyncImage
Phase"] + VM --> MemProto["SmartAsyncImageMemory
CacheProtocol"] + MemProto --> Mem["SmartAsyncImage
MemoryCache
(actor)"] + Mem --> Disk["SmartAsyncImage
DiskCache"] + Disk --> Encoder["SmartAsyncImage
Encoder"] + Mem --> URLSession[["URLSession"]] +``` + +--- + +## 🤖 Примечание об инструментах + +Часть работы над черновиками и редакторской доработкой в этом репозитории была ускорена с помощью больших языковых моделей (включая ChatGPT, Claude и Gemini) под непосредственным руководством, проверкой и окончательным утверждением человека. Все технические решения, код и архитектурные выводы создаются и проверяются мейнтейнером репозитория. + +--- + +## 🔐 Лицензия + +Лицензия MIT +Свободно для личного и коммерческого использования. + +--- + +## 👤 Автор + +Создано **Jonathan Ritchey** +Gentle Giraffe Apps +Старший iOS-инженер --- Swift | SwiftUI | Concurrency + +![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fgithub.com%2Fgentle-giraffe-apps%2FSmartAsyncImage) diff --git a/Docs/README.zh-CN.md b/Docs/README.zh-CN.md new file mode 100644 index 0000000..cbb0c30 --- /dev/null +++ b/Docs/README.zh-CN.md @@ -0,0 +1,165 @@ +# SmartAsyncImage + +一个更智能、更快速的 SwiftUI (iOS) `AsyncImage` 替代方案,内置内存和磁盘缓存、取消机制以及 Swift 6 并发支持。 + +[![CI](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gentle-giraffe-apps/SmartAsyncImage/actions/workflows/ci.yml) +[![Coverage](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage/branch/main/graph/badge.svg)](https://codecov.io/gh/gentle-giraffe-apps/SmartAsyncImage) +[![Swift](https://img.shields.io/badge/Swift-6.1+-orange.svg)](https://swift.org) +![Bazel](https://img.shields.io/badge/Bazel-enabled-555?logo=bazel) +[![SPM Compatible](https://img.shields.io/badge/SPM-Compatible-brightgreen.svg)](https://swift.org/package-manager/) +[![Platforms](https://img.shields.io/badge/platforms-iOS%2017%2B-blue)](https://developer.apple.com/ios/) +![Commit activity](https://img.shields.io/github/commit-activity/y/gentle-giraffe-apps/SmartAsyncImage) +![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) +[![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) + +> 🌍 **语言** · [English](../README.md) · [Español](README.es.md) · [Português (Brasil)](README.pt-BR.md) · [日本語](README.ja.md) · 简体中文 · [한국어](README.ko.md) · [Русский](README.ru.md) + +## 特性 +- 兼容 SwiftUI 的 API,配备可观察的视图模型 +- 智能阶段管理:`empty`、`loading`、`success(Image)`、`failure(Error)` +- 内存缓存协议,支持可插拔实现 +- 磁盘缓存,支持跨应用启动的持久化 +- Swift 并发(`async/await`)与协作式取消 +- MainActor 安全的状态更新 + +💬 **[参与讨论,欢迎反馈和提问](https://github.com/gentle-giraffe-apps/SmartAsyncImage/discussions)** + +## 环境要求 +- iOS 17+ +- Swift 6.1+ +- Swift Package Manager + +## 📦 安装(Swift Package Manager) + +### 通过 Xcode + +1. 在 Xcode 中打开你的项目 +2. 前往 **File → Add Packages...** +3. 输入仓库 URL:`https://github.com/gentle-giraffe-apps/SmartAsyncImage.git` +4. 选择版本规则(开发阶段可选 `main`) +5. 将 **SmartAsyncImage** 产品添加到你的应用目标 + +### 通过 `Package.swift` + +```swift +dependencies: [ + .package(url: "https://github.com/gentle-giraffe-apps/SmartAsyncImage.git", from: "1.0.0") +] +``` + +然后将 `"SmartAsyncImage"` 添加到目标的 `dependencies` 中。 + +## 示例应用 + +本仓库包含一个使用本地包引用的 SwiftUI 示例应用。 + +**路径:** +``` +Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj +``` + +### 运行方法 +1. 克隆仓库: + ```bash + git clone https://github.com/gentle-giraffe-apps/SmartAsyncImage.git + ``` +2. 打开示例项目: + ``` + Demo/SmartAsyncImageDemo/SmartAsyncImageDemo.xcodeproj + ``` +3. 选择 iOS 17+ 模拟器。 +4. 构建并运行(⌘R)。 + +该项目已预配置对 `SmartAsyncImage` 的本地 Swift Package 引用,无需额外配置即可运行。 + +## 用法 + +### 快速示例(SwiftUI) +```swift +import SwiftUI +import SmartAsyncImage + +struct MinimalRemoteImageView: View { + let imageURL = URL(string: "https://picsum.photos/300") + + var body: some View { + + // 替换前: AsyncImage(url: imageURL) { phase in + // ------------------------------------------------ + // 替换后: + + SmartAsyncImage(url: imageURL) { phase in + + // ------------------------------------------------ + + switch phase { + case .empty, .loading: + ProgressView() + case .success(let image): + image.resizable().scaledToFit() + case .failure: + Image(systemName: "photo") + } + } + .frame(width: 150, height: 150) + } +} +``` + +## 质量与工具 + +本项目通过 CI 和静态分析实施质量管控: + +- **CI:** 所有提交到 `main` 的代码必须通过 GitHub Actions 检查 +- **静态分析:** DeepSource 在每次提交到 `main` 时运行。 + 徽章显示当前未解决的静态分析问题数量。 +- **测试覆盖率:** Codecov 报告 `main` 分支的行覆盖率 + +Codecov 快照
+ + 按文件和模块划分的代码覆盖率快照(Codecov 树状图) + + +这些检查旨在确保设计系统能够安全地持续演进。 + +--- + +## 架构 + +```mermaid +flowchart TD + SAI["SmartAsyncImage
(SwiftUI View)"] --> VM["SmartAsyncImage
ViewModel"] + VM --> Phase["SmartAsyncImage
Phase"] + VM --> MemProto["SmartAsyncImageMemory
CacheProtocol"] + MemProto --> Mem["SmartAsyncImage
MemoryCache
(actor)"] + Mem --> Disk["SmartAsyncImage
DiskCache"] + Disk --> Encoder["SmartAsyncImage
Encoder"] + Mem --> URLSession[["URLSession"]] +``` + +--- + +## 🤖 工具说明 + +本仓库中部分文稿撰写和编辑润色借助了大语言模型(包括 ChatGPT、Claude 和 Gemini)加速完成,但均在人工直接设计、验证和最终审批下进行。所有技术决策、代码和架构结论均由仓库维护者编写和验证。 + +--- + +## 🔐 许可证 + +MIT 许可证 +可自由用于个人和商业用途。 + +--- + +## 👤 作者 + +由 **Jonathan Ritchey** 构建 +Gentle Giraffe Apps +高级 iOS 工程师 --- Swift | SwiftUI | Concurrency + +![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fgithub.com%2Fgentle-giraffe-apps%2FSmartAsyncImage) diff --git a/README.md b/README.md index d1c3335..ba062d4 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ A smarter, faster `AsyncImage` for SwiftUI (iOS) with built-in in-memory and dis ![Last commit](https://img.shields.io/github/last-commit/gentle-giraffe-apps/SmartAsyncImage) [![DeepSource](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage.svg/?label=active+issues&show_trend=true)](https://app.deepsource.com/gh/gentle-giraffe-apps/SmartAsyncImage/) -> 🌍 **Language** · English · [Español](Docs/README.es.md) · [Português (Brasil)](Docs/README.pt-BR.md) · [日本語](Docs/README.ja.md) +> 🌍 **Language** · English · [Español](Docs/README.es.md) · [Português (Brasil)](Docs/README.pt-BR.md) · [日本語](Docs/README.ja.md) · [简体中文](Docs/README.zh-CN.md) · [한국어](Docs/README.ko.md) · [Русский](Docs/README.ru.md) ## Features - SwiftUI-friendly API with an observable view model