Skip to content

Commit

Permalink
Merge branch 'main' into gh-page
Browse files Browse the repository at this point in the history
  • Loading branch information
rk0cc committed Jan 30, 2024
2 parents fe5e6cb + 4abfc00 commit 50e53e7
Show file tree
Hide file tree
Showing 18 changed files with 327 additions and 238 deletions.
33 changes: 33 additions & 0 deletions .github/workflows/autodl.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Auto download colour backup data
on:
schedule:
- cron: 0 10 15 1,4,7,10 *
workflow_dispatch:
jobs:
download:
name: Download colour data
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Download colours data
working-directory: lib/
run: curl -LO https://raw.githubusercontent.com/ozh/github-colors/master/colors.json
- name: Minify data
uses: StefanEnsmann/Minify-JSON-Action@1.1.0
with:
input_file: lib/colors.json
- name: Config Git
id: gitconf
run: |
git config --local user.name "Colour fetch"
git config --local user.email "enquiry@rk0cc.xyz"
git add .
git commit -m "Update colour backup data"
- name: Push
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: main
1 change: 1 addition & 0 deletions .pubignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ docs/
/example/pubspec.lock
/example/pubspec.yaml
/example/README.md
/colour_download.ps1
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## 3.1.0

* Drop Dart 2 support
* Mark some classes as immutable
* Improved source code directory layout
* Lints

## 3.0.0

* Dart 3 supported
Expand Down
29 changes: 29 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
11 changes: 4 additions & 7 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ class App extends StatelessWidget {

@override
Widget build(BuildContext context) => MaterialApp(
title: 'GitHub Language colour',
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: GoogleFonts.robotoTextTheme()),
home: const GitHubColourDemo(),
);
title: 'GitHub Language colour',
theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: false, textTheme: GoogleFonts.robotoTextTheme()),
home: const GitHubColourDemo());
}

class GitHubColourDemo extends StatefulWidget {
Expand Down Expand Up @@ -124,6 +121,6 @@ class _GitHubColourDemoState extends State<GitHubColourDemo> {
width: 80,
height: 35,
child: ElevatedButton(
child: const Text("Apply"), onPressed: _changeColour))
onPressed: _changeColour, child: const Text("Apply")))
])));
}
4 changes: 2 additions & 2 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: A new Flutter project.
publish_to: 'none'
version: 2.0.0
environment:
sdk: ">=2.17.0 <4.0.0"
sdk: ">=3.0.0 <4.0.0"
dependencies:
flutter:
sdk: flutter
Expand All @@ -14,6 +14,6 @@ dependencies:
font_awesome_flutter: ^10.4.0
google_fonts: ^4.0.5
dev_dependencies:
flutter_lints: ^2.0.0
flutter_lints: ^3.0.1
flutter:
uses-material-design: true
2 changes: 1 addition & 1 deletion lib/colors.json

Large diffs are not rendered by default.

213 changes: 1 addition & 212 deletions lib/github_colour.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,217 +3,6 @@
/// [Color].
library github_colour;

import 'dart:collection';
import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart'
show Color, ColorSwatch, WidgetsFlutterBinding;
import 'package:http/http.dart' as http show get;
import 'package:meta/meta.dart' show sealed;

import 'src/cache/cache.dart';
import 'src/cache/exception.dart';
import 'src/exception.dart';

export 'src/cache/exception.dart';
export 'src/exception.dart';

const String _src =
"https://raw.githubusercontent.com/ozh/github-colors/master/colors.json";

/// An [Error] thrown when response unsuccessfully and no cache can be used.
class GitHubColourHTTPLoadFailedError extends GitHubColourLoadFailedError {
/// HTTP response code when fetching colour data.
final int responseCode;

GitHubColourHTTPLoadFailedError._(this.responseCode)
: assert(responseCode != 200),
super();

@override
String toString() =>
"GitHubColourLoadFailedError: Can not receive GitHub language colour from server with HTTP code $responseCode.";
}

/// An [Error] thrown when no resources available to initalize [GitHubColour].
class GitHubColourNoAvailableResourceError extends GitHubColourLoadFailedError {
GitHubColourNoAvailableResourceError._() : super();

@override
String toString() =>
"GitHubColourNoAvailableResourceError: Unable to read GitHub colour data with all available sources.";
}

Color _hex2C(String hex, [String alphaHex = "ff"]) {
assert(RegExp(r"^#[0-9a-f]{6}$", caseSensitive: false).hasMatch(hex));
assert(RegExp(r"^[0-9a-f]{2}$", caseSensitive: false).hasMatch(alphaHex));

return Color(
int.parse("$alphaHex${hex.substring(1)}".toUpperCase(), radix: 16));
}

Map<String, Color> _colourReader(String json) =>
(jsonDecode(json) as Map<String, dynamic>).map<String, Color>(
(language, node) => MapEntry(
language, _hex2C(node["color"] ?? GitHubColour._defaultColourHex)));

/// A class for getting GitHub language colour.
///
/// Since 2.0.0, [GitHubColour] implemented [ColorSwatch] that getting colour
/// can be more convenience. And serval old API will be [Deprecated].
@sealed
class GitHubColour extends UnmodifiableMapBase<String, Color>
implements ColorSwatch<String> {
static GitHubColour? _instance;
final Map<String, Color> _githubLangColour;

/// A [String] of hex value when the language is undefined or null.
static const String _defaultColourHex = "#f0f0f0";

/// [Color] object of [defaultColourHex].
static Color get _defaultColour => _hex2C(_defaultColourHex);

GitHubColour._(Map<String, Color> githubLangColour)
: this._githubLangColour = Map.unmodifiable(githubLangColour);

/// Construct an instance of [GitHubColour].
///
/// If [offlineLastResort] enabled, it loads package's `colors.json` for
/// getting colour data offline. And it must be called after
/// [WidgetsFlutterBinding.ensureInitialized] invoked in `main()` method to
/// allow get offline colour data from [rootBundle].
///
/// When all resources failed, it throws
/// [GitHubColourNoAvailableResourceError]. If [offlineLastResort] disabled,
/// either [GitHubColourHTTPLoadFailedError] (if network available) or
/// [Exception] that repersenting no network state (e.g
/// [SocketException](https://api.dart.dev/stable/dart-io/SocketException-class.html)
/// in `"dart:io"` package).
///
/// [offlineLastResort] only works when [initialize] invoked first time
/// in entire runtime. This parameter will be ignored once the instance
/// constructed.
///
/// Since `1.2.0`, it added chechsum validation on the cache. When the cache's
/// checksum does not matched, it throws
/// [GitHubColourCacheChecksumMismatchedError].
static Future<void> initialize({bool offlineLastResort = true}) async {
if (_instance == null) {
final Uri ghc = Uri.parse(_src);
Map<String, Color> ghjson;

bool cacheSource = false;

try {
var resp = await http.get(ghc);
if (resp.statusCode != 200) {
throw GitHubColourHTTPLoadFailedError._(resp.statusCode);
}
ghjson = _colourReader(resp.body);
} catch (neterr) {
try {
// Second source.
ghjson = await getCache();
cacheSource = true;
} catch (cerr) {
if (!offlineLastResort) {
// When offline last resort disabled.
throw neterr;
}

try {
// Use provided JSON file as last resort.
ghjson = _colourReader(await rootBundle.loadString(
"packages/github_colour/colors.json",
cache: false));
} catch (bundleerr) {
throw GitHubColourNoAvailableResourceError._();
}
}
}

if (!cacheSource) {
// Do nothing if received data is exact same with source.
await saveCache(ghjson);
}

_instance = GitHubColour._(ghjson);
}
}

/// Perform [initialize] and return [GitHubColour].
///
/// If no instance created, it will construct and will be reused when
/// [getInstance] or [getExistedInstance] called again.
///
/// This method is deprecated since it may not required to uses [GitHubColour]
/// once the instance created.
@Deprecated("Please call void function `initialize()`")
static Future<GitHubColour> getInstance(
{bool offlineLastResort = true}) async {
await initialize(offlineLastResort: offlineLastResort);

return _instance!;
}

/// Get constructed instance which called [initialize] early.
///
/// It throws [UnimplementedError] if called with no existed instance.
static GitHubColour getExistedInstance() {
if (_instance == null) {
throw UnimplementedError("No existed instance found in GitHubColour");
}

return _instance!;
}

/// Resolve [key] as language and find repersented [Color] from providers.
///
/// If [key] is undefined, it returns default colour instead.
@override
Color operator [](Object? key) => _githubLangColour[key] ?? _defaultColour;

@override
int get alpha => _defaultColour.red;

@override
int get blue => _defaultColour.blue;

@override
double computeLuminance() => _defaultColour.computeLuminance();

@override
int get green => _defaultColour.green;

@override
Iterable<String> get keys => Set.unmodifiable(_githubLangColour.keys);

@override
double get opacity => _defaultColour.opacity;

@override
int get red => _defaultColour.red;

@override
int get value => _defaultColour.value;

@override
Color withAlpha(int a) => _defaultColour.withAlpha(a);

@override
Color withBlue(int b) => _defaultColour.withBlue(b);

@override
Color withGreen(int g) => _defaultColour.withGreen(g);

@override
Color withOpacity(double opacity) => _defaultColour.withOpacity(opacity);

@override
Color withRed(int r) => _defaultColour.withRed(r);
}

/// Alias type for repersenting "colour" in American English which does exactly
/// same with [GitHubColour].
typedef GitHubColor = GitHubColour;
export 'src/swatch.dart';
3 changes: 3 additions & 0 deletions lib/src/cache/cache_generic.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import 'package:flutter/widgets.dart' show Color;
import 'package:meta/meta.dart' show internal;

@internal
Future<void> saveCache(Map<String, Color> githubColour) async {
throw UnsupportedError("No implementation in this platform");
}

@internal
Future<Map<String, Color>> getCache() async {
throw UnsupportedError("No implementation in this platform");
}
3 changes: 3 additions & 0 deletions lib/src/cache/cache_vm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import "dart:io";
import 'dart:typed_data';

import 'package:flutter/widgets.dart' show Color;
import 'package:meta/meta.dart';
import "package:path/path.dart" as path;
import "package:path_provider/path_provider.dart" as path_provider;

Expand Down Expand Up @@ -45,6 +46,7 @@ Future<File> get _cacheChecksum async {
return checksum;
}

@internal
Future<void> saveCache(Map<String, Color> githubColour) async {
File tf = await _cacheFile;
File cf = await _cacheChecksum;
Expand All @@ -57,6 +59,7 @@ Future<void> saveCache(Map<String, Color> githubColour) async {
}
}

@internal
Future<Map<String, Color>> getCache() async {
File tf = await _cacheFile;

Expand Down
Loading

0 comments on commit 50e53e7

Please sign in to comment.