file_path
stringlengths 3
280
| file_language
stringclasses 66
values | content
stringlengths 1
1.04M
| repo_name
stringlengths 5
92
| repo_stars
int64 0
154k
| repo_description
stringlengths 0
402
| repo_primary_language
stringclasses 108
values | developer_username
stringlengths 1
25
| developer_name
stringlengths 0
30
| developer_company
stringlengths 0
82
|
|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/zmb/sunshine/data/WeatherProvider.java
|
Java
|
package com.zmb.sunshine.data;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import com.zmb.sunshine.data.db.WeatherContract;
import com.zmb.sunshine.data.db.WeatherDbHelper;
/**
* A content provider for our weather data.
*/
public class WeatherProvider extends ContentProvider {
// each URI in the content provider is tied to an integer constant
private static final int WEATHER = 100;
private static final int WEATHER_WITH_LOCATION = 101;
private static final int WEATHER_WITH_LOCATION_AND_DATE = 102;
private static final int LOCATION = 300;
private static final int LOCATION_ID = 301;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final SQLiteQueryBuilder sQueryBuilder = new SQLiteQueryBuilder();
private static final String sLocationSelection;
private static final String sLocationSelectionWithStartDate;
private static final String sLocationSelectionWithExactDate;
private WeatherDbHelper mOpenHelper;
static {
sQueryBuilder.setTables(WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " +
WeatherContract.LocationEntry.TABLE_NAME + " ON " +
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY +
" = " + WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry._ID);
// '?' character will be replaced by query parameters
sLocationSelection = WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
sLocationSelectionWithStartDate = WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATETEXT + " >= ? ";
sLocationSelectionWithExactDate = WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATETEXT + " = ? ";
}
@Override
public boolean onCreate() {
mOpenHelper = new WeatherDbHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor result = null;
switch (sUriMatcher.match(uri)) {
case WEATHER:
result = mOpenHelper.getReadableDatabase().query(
WeatherContract.WeatherEntry.TABLE_NAME,
projection, selection, selectionArgs, null, null, sortOrder);
break;
case WEATHER_WITH_LOCATION:
result = getWeatherByLocation(uri, projection, sortOrder);
break;
case WEATHER_WITH_LOCATION_AND_DATE:
result = getWeatherByLocationWithExactDate(uri, projection, sortOrder);
break;
case LOCATION:
result = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection, selection, selectionArgs, null, null, sortOrder);
break;
case LOCATION_ID:
result = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection, WeatherContract.LocationEntry._ID + " = '" + ContentUris.parseId(uri) + "'",
null, null, null, sortOrder);
break;
}
if (result != null) {
// causes the cursor to register a content observer to watch for
// changes at the specified URI and its descendants
result.setNotificationUri(getContext().getContentResolver(), uri);
}
return result;
}
@Override
public String getType(Uri uri) {
// return MIME type associated with the data at the given URI
final int match = sUriMatcher.match(uri);
switch (match) {
case WEATHER:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case WEATHER_WITH_LOCATION:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case WEATHER_WITH_LOCATION_AND_DATE:
return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE;
case LOCATION:
// can return multiple rows
return WeatherContract.LocationEntry.CONTENT_TYPE;
case LOCATION_ID:
// only a single row will ever match a location ID
return WeatherContract.LocationEntry.CONTENT_ITEM_TYPE;
default: throw new UnsupportedOperationException("Unknown URI: " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
final int match = sUriMatcher.match(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Uri result;
// we only allow insertions at the root URI to make it easy
// to handle notifications when new data is inserted
switch (match) {
case WEATHER:
long id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, contentValues);
if (id != -1) {
result = WeatherContract.WeatherEntry.buildWeatherUri(id);
} else {
throw new android.database.SQLException("Failed to insert row into " + uri);
}
break;
case LOCATION:
id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, contentValues);
if (id != -1) {
result = WeatherContract.LocationEntry.buildLocationUri(id);
} else {
throw new android.database.SQLException("Failed to insert row into " + uri);
}
break;
default:
throw new UnsupportedOperationException("Unknown URI: " + uri);
}
// notify any registered observers that the data changed
getContext().getContentResolver().notifyChange(uri, null);
return result;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final int match = sUriMatcher.match(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int deleted;
switch (match) {
case WEATHER:
deleted = db.delete(WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs);
break;
case LOCATION:
deleted = db.delete(WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
deleted = 0;
break;
}
// null selection deletes all rows
if (selection == null || deleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return deleted;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final int match = sUriMatcher.match(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int updated;
switch (match) {
case WEATHER:
updated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection, selectionArgs);
break;
case LOCATION:
updated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection, selectionArgs);
break;
default:
updated = 0;
break;
}
if (updated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return updated;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
switch (match)
{
case WEATHER:
db.beginTransaction();
int count = 0;
try {
for (ContentValues value : values) {
long id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (id != -1) { ++count; }
}
db.setTransactionSuccessful();
} finally {
// commits the updates
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
default:
return super.bulkInsert(uri, values);
}
}
private static UriMatcher buildUriMatcher() {
// root node shouldn't match anything
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(WeatherContract.CONTENT_AUTHORITY, WeatherContract.PATH_WEATHER, WEATHER);
// date is always numeric, but we store it in the DB as a string ("*" character)
matcher.addURI(WeatherContract.CONTENT_AUTHORITY, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION);
matcher.addURI(WeatherContract.CONTENT_AUTHORITY, WeatherContract.PATH_WEATHER + "/*/*", WEATHER_WITH_LOCATION_AND_DATE);
// location ID is always numeric
matcher.addURI(WeatherContract.CONTENT_AUTHORITY, WeatherContract.PATH_LOCATION, LOCATION);
matcher.addURI(WeatherContract.CONTENT_AUTHORITY, WeatherContract.PATH_LOCATION + "/#", LOCATION_ID);
return matcher;
}
private Cursor getWeatherByLocation(Uri uri, String[] projection, String sortOrder) {
String location = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
String startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri);
String endDate = WeatherContract.WeatherEntry.getEndDateFromUri(uri);
String selection;
String[] selectionArgs;
if (startDate == null) {
selection = sLocationSelection;
selectionArgs = new String[] { location };
} else if (endDate != null) {
// we have a start AND end date
selection = sLocationSelectionWithStartDate + " AND " +
WeatherContract.WeatherEntry.COLUMN_DATETEXT + " < ? ";
selectionArgs = new String[] { location, startDate, endDate };
} else {
selection = sLocationSelectionWithStartDate;
selectionArgs = new String[] { location, startDate };
}
return sQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection,
selection, selectionArgs, null, null, sortOrder);
}
private Cursor getWeatherByLocationWithExactDate(Uri uri, String[] projection, String sortOrder) {
String location = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
String date = WeatherContract.WeatherEntry.getDateFromUri(uri);
return sQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection,
sLocationSelectionWithExactDate, new String[] { location, date },
null, null, sortOrder);
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/data/db/AndroidDatabaseManager.java
|
Java
|
package com.zmb.sunshine.data.db;
/**
* Created by zberg_000 on 12/1/2014.
*/
import java.util.ArrayList;
import java.util.LinkedList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidDatabaseManager extends Activity implements OnItemClickListener {
//a static class to save cursor,table values etc which is used by functions to share data in the program.
static class indexInfo {
public static int index = 10;
public static int numberofpages = 0;
public static int currentpage = 0;
public static String table_name = "";
public static Cursor maincursor;
public static int cursorpostion = 0;
public static ArrayList<String> value_string;
public static ArrayList<String> tableheadernames;
public static ArrayList<String> emptytablecolumnnames;
public static boolean isEmpty;
public static boolean isCustomQuery;
}
// all global variables
//in the below line Change the text 'yourCustomSqlHelper' with your custom sqlitehelper class name.
//Do not change the variable name dbm
WeatherDbHelper dbm;
TableLayout tableLayout;
TableRow.LayoutParams tableRowParams;
HorizontalScrollView hsv;
ScrollView mainscrollview;
LinearLayout mainLayout;
TextView tvmessage;
Button previous;
Button next;
Spinner select_table;
TextView tv;
indexInfo info = new indexInfo();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//in the below line Change the text 'yourCustomSqlHelper' with your custom sqlitehelper class name
dbm = new WeatherDbHelper(AndroidDatabaseManager.this);
mainscrollview = new ScrollView(AndroidDatabaseManager.this);
//the main linear layout to which all tables spinners etc will be added.In this activity every element is created dynamically to avoid using xml file
mainLayout = new LinearLayout(AndroidDatabaseManager.this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
mainLayout.setBackgroundColor(Color.WHITE);
mainLayout.setScrollContainer(true);
mainscrollview.addView(mainLayout);
//all required layouts are created dynamically and added to the main scrollview
setContentView(mainscrollview);
//the first row of layout which has a text view and spinner
final LinearLayout firstrow = new LinearLayout(AndroidDatabaseManager.this);
firstrow.setPadding(0, 10, 0, 20);
LinearLayout.LayoutParams firstrowlp = new LinearLayout.LayoutParams(0, 150);
firstrowlp.weight = 1;
TextView maintext = new TextView(AndroidDatabaseManager.this);
maintext.setText("Select Table");
maintext.setTextSize(22);
maintext.setLayoutParams(firstrowlp);
select_table = new Spinner(AndroidDatabaseManager.this);
select_table.setLayoutParams(firstrowlp);
firstrow.addView(maintext);
firstrow.addView(select_table);
mainLayout.addView(firstrow);
ArrayList<Cursor> alc;
//the horizontal scroll view for table if the table content doesnot fit into screen
hsv = new HorizontalScrollView(AndroidDatabaseManager.this);
//the main table layout where the content of the sql tables will be displayed when user selects a table
tableLayout = new TableLayout(AndroidDatabaseManager.this);
tableLayout.setHorizontalScrollBarEnabled(true);
hsv.addView(tableLayout);
//the second row of the layout which shows number of records in the table selected by user
final LinearLayout secondrow = new LinearLayout(AndroidDatabaseManager.this);
secondrow.setPadding(0, 20, 0, 10);
LinearLayout.LayoutParams secondrowlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
secondrowlp.weight = 1;
TextView secondrowtext = new TextView(AndroidDatabaseManager.this);
secondrowtext.setText("No. Of Records : ");
secondrowtext.setTextSize(20);
secondrowtext.setLayoutParams(secondrowlp);
tv = new TextView(AndroidDatabaseManager.this);
tv.setTextSize(20);
tv.setLayoutParams(secondrowlp);
secondrow.addView(secondrowtext);
secondrow.addView(tv);
mainLayout.addView(secondrow);
//A button which generates a text view from which user can write custome queries
final EditText customquerytext = new EditText(this);
customquerytext.setVisibility(View.GONE);
customquerytext.setHint("Enter Your Query here and Click on Submit Query Button .Results will be displayed below");
mainLayout.addView(customquerytext);
final Button submitQuery = new Button(AndroidDatabaseManager.this);
submitQuery.setVisibility(View.GONE);
submitQuery.setText("Submit Query");
submitQuery.setBackgroundColor(Color.parseColor("#BAE7F6"));
mainLayout.addView(submitQuery);
final TextView help = new TextView(AndroidDatabaseManager.this);
help.setText("Click on the row below to update values or delete the tuple");
help.setPadding(0, 5, 0, 5);
// the spinner which gives user a option to add new row , drop or delete table
final Spinner spinnertable = new Spinner(AndroidDatabaseManager.this);
mainLayout.addView(spinnertable);
mainLayout.addView(help);
hsv.setPadding(0, 10, 0, 10);
hsv.setScrollbarFadingEnabled(false);
hsv.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
mainLayout.addView(hsv);
//the third layout which has buttons for the pagination of content from database
final LinearLayout thirdrow = new LinearLayout(AndroidDatabaseManager.this);
previous = new Button(AndroidDatabaseManager.this);
previous.setText("Previous");
previous.setBackgroundColor(Color.parseColor("#BAE7F6"));
previous.setLayoutParams(secondrowlp);
next = new Button(AndroidDatabaseManager.this);
next.setText("Next");
next.setBackgroundColor(Color.parseColor("#BAE7F6"));
next.setLayoutParams(secondrowlp);
TextView tvblank = new TextView(this);
tvblank.setLayoutParams(secondrowlp);
thirdrow.setPadding(0, 10, 0, 10);
thirdrow.addView(previous);
thirdrow.addView(tvblank);
thirdrow.addView(next);
mainLayout.addView(thirdrow);
//the text view at the bottom of the screen which displays error or success messages after a query is executed
tvmessage = new TextView(AndroidDatabaseManager.this);
tvmessage.setText("Error Messages will be displayed here");
String Query = "SELECT name _id FROM sqlite_master WHERE type ='table'";
tvmessage.setTextSize(18);
mainLayout.addView(tvmessage);
final Button customQuery = new Button(AndroidDatabaseManager.this);
customQuery.setText("Custom Query");
customQuery.setBackgroundColor(Color.parseColor("#BAE7F6"));
mainLayout.addView(customQuery);
customQuery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//set drop down to custom Query
indexInfo.isCustomQuery = true;
secondrow.setVisibility(View.GONE);
spinnertable.setVisibility(View.GONE);
help.setVisibility(View.GONE);
customquerytext.setVisibility(View.VISIBLE);
submitQuery.setVisibility(View.VISIBLE);
select_table.setSelection(0);
customQuery.setVisibility(View.GONE);
}
});
//when user enter a custom query in text view and clicks on submit query button
//display results in tablelayout
submitQuery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tableLayout.removeAllViews();
customQuery.setVisibility(View.GONE);
ArrayList<Cursor> alc2;
String Query10 = customquerytext.getText().toString();
Log.d("query", Query10);
//pass the query to getdata method and get results
alc2 = dbm.getData(Query10);
final Cursor c4 = alc2.get(0);
Cursor Message2 = alc2.get(1);
Message2.moveToLast();
//if the query returns results display the results in table layout
if (Message2.getString(0).equalsIgnoreCase("Success")) {
tvmessage.setBackgroundColor(Color.parseColor("#2ecc71"));
tvmessage.setText("Queru Executed successfully.Number of rows returned :" + c4.getCount());
if (c4.getCount() > 0) {
indexInfo.maincursor = c4;
refreshTable(1);
}
} else {
//if there is any error we displayed the error message at the bottom of the screen
tvmessage.setBackgroundColor(Color.parseColor("#e74c3c"));
tvmessage.setText("Error:" + Message2.getString(0));
}
}
});
//layout parameters for each row in the table
tableRowParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 0, 2, 0);
// a query which returns a cursor with the list of tables in the database.We use this cursor to populate spinner in the first row
alc = dbm.getData(Query);
//the first cursor has reults of the query
final Cursor c = alc.get(0);
//the second cursor has error messages
Cursor Message = alc.get(1);
Message.moveToLast();
String msg = Message.getString(0);
Log.d("Message from sql = ", msg);
ArrayList<String> tablenames = new ArrayList<String>();
if (c != null) {
c.moveToFirst();
tablenames.add("click here");
do {
//add names of the table to tablenames array list
tablenames.add(c.getString(0));
} while (c.moveToNext());
}
//an array adapter with above created arraylist
ArrayAdapter<String> tablenamesadapter = new ArrayAdapter<String>(AndroidDatabaseManager.this,
android.R.layout.simple_spinner_item, tablenames) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setBackgroundColor(Color.WHITE);
TextView adap = (TextView) v;
adap.setTextSize(20);
return adap;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v = super.getDropDownView(position, convertView, parent);
v.setBackgroundColor(Color.WHITE);
return v;
}
};
tablenamesadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if (tablenamesadapter != null) {
//set the adpater to select_table spinner
select_table.setAdapter(tablenamesadapter);
}
// when a table names is selecte display the table contents
select_table.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (pos == 0 && !indexInfo.isCustomQuery) {
secondrow.setVisibility(View.GONE);
hsv.setVisibility(View.GONE);
thirdrow.setVisibility(View.GONE);
spinnertable.setVisibility(View.GONE);
help.setVisibility(View.GONE);
tvmessage.setVisibility(View.GONE);
customquerytext.setVisibility(View.GONE);
submitQuery.setVisibility(View.GONE);
customQuery.setVisibility(View.GONE);
}
if (pos != 0) {
secondrow.setVisibility(View.VISIBLE);
spinnertable.setVisibility(View.VISIBLE);
help.setVisibility(View.VISIBLE);
customquerytext.setVisibility(View.GONE);
submitQuery.setVisibility(View.GONE);
customQuery.setVisibility(View.VISIBLE);
hsv.setVisibility(View.VISIBLE);
tvmessage.setVisibility(View.VISIBLE);
thirdrow.setVisibility(View.VISIBLE);
c.moveToPosition(pos - 1);
indexInfo.cursorpostion = pos - 1;
//displaying the content of the table which is selected in the select_table spinner
Log.d("selected table name is", "" + c.getString(0));
indexInfo.table_name = c.getString(0);
tvmessage.setText("Error Messages will be displayed here");
tvmessage.setBackgroundColor(Color.WHITE);
//removes any data if present in the table layout
tableLayout.removeAllViews();
ArrayList<String> spinnertablevalues = new ArrayList<String>();
spinnertablevalues.add("Click here to change this table");
spinnertablevalues.add("Add row to this table");
spinnertablevalues.add("Delete this table");
spinnertablevalues.add("Drop this table");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, spinnertablevalues);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
// a array adapter which add values to the spinner which helps in user making changes to the table
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AndroidDatabaseManager.this,
android.R.layout.simple_spinner_item, spinnertablevalues) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setBackgroundColor(Color.WHITE);
TextView adap = (TextView) v;
adap.setTextSize(20);
return adap;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v = super.getDropDownView(position, convertView, parent);
v.setBackgroundColor(Color.WHITE);
return v;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnertable.setAdapter(adapter);
String Query2 = "select * from " + c.getString(0);
Log.d("", "" + Query2);
//getting contents of the table which user selected from the select_table spinner
ArrayList<Cursor> alc2 = dbm.getData(Query2);
final Cursor c2 = alc2.get(0);
//saving cursor to the static indexinfo class which can be resued by the other functions
indexInfo.maincursor = c2;
// if the cursor returned form the database is not null we display the data in table layout
if (c2 != null) {
int counts = c2.getCount();
indexInfo.isEmpty = false;
Log.d("counts", "" + counts);
tv.setText("" + counts);
//the spinnertable has the 3 items to drop , delete , add row to the table selected by the user
//here we handle the 3 operations.
spinnertable.setOnItemSelectedListener((new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
((TextView) parentView.getChildAt(0)).setTextColor(Color.rgb(0, 0, 0));
//when user selects to drop the table the below code in if block will be executed
if (spinnertable.getSelectedItem().toString().equals("Drop this table")) {
// an alert dialog to confirm user selection
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isFinishing()) {
new AlertDialog.Builder(AndroidDatabaseManager.this)
.setTitle("Are you sure ?")
.setMessage("Pressing yes will remove " + indexInfo.table_name + " table from database")
.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
// when user confirms by clicking on yes we drop the table by executing drop table query
public void onClick(DialogInterface dialog, int which) {
String Query6 = "Drop table " + indexInfo.table_name;
ArrayList<Cursor> aldropt = dbm.getData(Query6);
Cursor tempc = aldropt.get(1);
tempc.moveToLast();
Log.d("Drop table Mesage", tempc.getString(0));
if (tempc.getString(0).equalsIgnoreCase("Success")) {
tvmessage.setBackgroundColor(Color.parseColor("#2ecc71"));
tvmessage.setText(indexInfo.table_name + "Dropped successfully");
refreshactivity();
} else {
//if there is any error we displayd the error message at the bottom of the screen
tvmessage.setBackgroundColor(Color.parseColor("#e74c3c"));
tvmessage.setText("Error:" + tempc.getString(0));
spinnertable.setSelection(0);
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
spinnertable.setSelection(0);
}
})
.create().show();
}
}
});
}
//when user selects to drop the table the below code in if block will be executed
if (spinnertable.getSelectedItem().toString().equals("Delete this table")) { // an alert dialog to confirm user selection
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isFinishing()) {
new AlertDialog.Builder(AndroidDatabaseManager.this)
.setTitle("Are you sure?")
.setMessage("Clicking on yes will delete all the contents of " + indexInfo.table_name + " table from database")
.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
// when user confirms by clicking on yes we drop the table by executing delete table query
public void onClick(DialogInterface dialog, int which) {
String Query7 = "Delete from " + indexInfo.table_name;
Log.d("delete table query", Query7);
ArrayList<Cursor> aldeletet = dbm.getData(Query7);
Cursor tempc = aldeletet.get(1);
tempc.moveToLast();
Log.d("Delete table Mesage", tempc.getString(0));
if (tempc.getString(0).equalsIgnoreCase("Success")) {
tvmessage.setBackgroundColor(Color.parseColor("#2ecc71"));
tvmessage.setText(indexInfo.table_name + " table content deleted successfully");
indexInfo.isEmpty = true;
refreshTable(0);
} else {
tvmessage.setBackgroundColor(Color.parseColor("#e74c3c"));
tvmessage.setText("Error:" + tempc.getString(0));
spinnertable.setSelection(0);
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
spinnertable.setSelection(0);
}
})
.create().show();
}
}
});
}
//when user selects to add row to the table the below code in if block will be executed
if (spinnertable.getSelectedItem().toString().equals("Add row to this table")) {
//we create a layout which has textviews with column names of the table and edittexts where
//user can enter value which will be inserted into the datbase.
final LinkedList<TextView> addnewrownames = new LinkedList<TextView>();
final LinkedList<EditText> addnewrowvalues = new LinkedList<EditText>();
final ScrollView addrowsv = new ScrollView(AndroidDatabaseManager.this);
Cursor c4 = indexInfo.maincursor;
if (indexInfo.isEmpty) {
getcolumnnames();
for (int i = 0; i < indexInfo.emptytablecolumnnames.size(); i++) {
String cname = indexInfo.emptytablecolumnnames.get(i);
TextView tv = new TextView(getApplicationContext());
tv.setText(cname);
addnewrownames.add(tv);
}
for (int i = 0; i < addnewrownames.size(); i++) {
EditText et = new EditText(getApplicationContext());
addnewrowvalues.add(et);
}
} else {
for (int i = 0; i < c4.getColumnCount(); i++) {
String cname = c4.getColumnName(i);
TextView tv = new TextView(getApplicationContext());
tv.setText(cname);
addnewrownames.add(tv);
}
for (int i = 0; i < addnewrownames.size(); i++) {
EditText et = new EditText(getApplicationContext());
addnewrowvalues.add(et);
}
}
final RelativeLayout addnewlayout = new RelativeLayout(AndroidDatabaseManager.this);
RelativeLayout.LayoutParams addnewparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
addnewparams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
for (int i = 0; i < addnewrownames.size(); i++) {
TextView tv = addnewrownames.get(i);
EditText et = addnewrowvalues.get(i);
int t = i + 400;
int k = i + 500;
int lid = i + 600;
tv.setId(t);
tv.setTextColor(Color.parseColor("#000000"));
et.setBackgroundColor(Color.parseColor("#F2F2F2"));
et.setTextColor(Color.parseColor("#000000"));
et.setId(k);
final LinearLayout ll = new LinearLayout(AndroidDatabaseManager.this);
LinearLayout.LayoutParams tvl = new LinearLayout.LayoutParams(0, 100);
tvl.weight = 1;
ll.addView(tv, tvl);
ll.addView(et, tvl);
ll.setId(lid);
Log.d("Edit Text Value", "" + et.getText().toString());
RelativeLayout.LayoutParams rll = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rll.addRule(RelativeLayout.BELOW, ll.getId() - 1);
rll.setMargins(0, 20, 0, 0);
addnewlayout.addView(ll, rll);
}
addnewlayout.setBackgroundColor(Color.WHITE);
addrowsv.addView(addnewlayout);
Log.d("Button Clicked", "");
//the above form layout which we have created above will be displayed in an alert dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isFinishing()) {
new AlertDialog.Builder(AndroidDatabaseManager.this)
.setTitle("values")
.setCancelable(false)
.setView(addrowsv)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
// after entering values if user clicks on add we take the values and run a insert query
public void onClick(DialogInterface dialog, int which) {
indexInfo.index = 10;
//tableLayout.removeAllViews();
//trigger select table listener to be triggerd
String Query4 = "Insert into " + indexInfo.table_name + " (";
for (int i = 0; i < addnewrownames.size(); i++) {
TextView tv = addnewrownames.get(i);
tv.getText().toString();
if (i == addnewrownames.size() - 1) {
Query4 = Query4 + tv.getText().toString();
} else {
Query4 = Query4 + tv.getText().toString() + ", ";
}
}
Query4 = Query4 + " ) VALUES ( ";
for (int i = 0; i < addnewrownames.size(); i++) {
EditText et = addnewrowvalues.get(i);
et.getText().toString();
if (i == addnewrownames.size() - 1) {
Query4 = Query4 + "'" + et.getText().toString() + "' ) ";
} else {
Query4 = Query4 + "'" + et.getText().toString() + "' , ";
}
}
//this is the insert query which has been generated
Log.d("Insert Query", Query4);
ArrayList<Cursor> altc = dbm.getData(Query4);
Cursor tempc = altc.get(1);
tempc.moveToLast();
Log.d("Add New Row", tempc.getString(0));
if (tempc.getString(0).equalsIgnoreCase("Success")) {
tvmessage.setBackgroundColor(Color.parseColor("#2ecc71"));
tvmessage.setText("New Row added succesfully to " + indexInfo.table_name);
refreshTable(0);
} else {
tvmessage.setBackgroundColor(Color.parseColor("#e74c3c"));
tvmessage.setText("Error:" + tempc.getString(0));
spinnertable.setSelection(0);
}
}
})
.setNegativeButton("close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
spinnertable.setSelection(0);
}
})
.create().show();
}
}
});
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}));
//display the first row of the table with column names of the table selected by the user
TableRow tableheader = new TableRow(getApplicationContext());
tableheader.setBackgroundColor(Color.BLACK);
tableheader.setPadding(0, 2, 0, 2);
for (int k = 0; k < c2.getColumnCount(); k++) {
LinearLayout cell = new LinearLayout(AndroidDatabaseManager.this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(tableRowParams);
final TextView tableheadercolums = new TextView(getApplicationContext());
// tableheadercolums.setBackgroundDrawable(gd);
tableheadercolums.setPadding(0, 0, 4, 3);
tableheadercolums.setText("" + c2.getColumnName(k));
tableheadercolums.setTextColor(Color.parseColor("#000000"));
//columsView.setLayoutParams(tableRowParams);
cell.addView(tableheadercolums);
tableheader.addView(cell);
}
tableLayout.addView(tableheader);
c2.moveToFirst();
//after displaying columnnames in the first row we display data in the remaining columns
//the below paginatetbale function will display the first 10 tuples of the tables
//the remaining tuples can be viewed by clicking on the next button
paginatetable(c2.getCount());
} else {
//if the cursor returned from the database is empty we show that table is empty
help.setVisibility(View.GONE);
tableLayout.removeAllViews();
getcolumnnames();
TableRow tableheader2 = new TableRow(getApplicationContext());
tableheader2.setBackgroundColor(Color.BLACK);
tableheader2.setPadding(0, 2, 0, 2);
LinearLayout cell = new LinearLayout(AndroidDatabaseManager.this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(tableRowParams);
final TextView tableheadercolums = new TextView(getApplicationContext());
tableheadercolums.setPadding(0, 0, 4, 3);
tableheadercolums.setText(" Table Is Empty ");
tableheadercolums.setTextSize(30);
tableheadercolums.setTextColor(Color.RED);
cell.addView(tableheadercolums);
tableheader2.addView(cell);
tableLayout.addView(tableheader2);
tv.setText("" + 0);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
//get columnnames of the empty tables and save them in a array list
public void getcolumnnames() {
ArrayList<Cursor> alc3 = dbm.getData("PRAGMA table_info(" + indexInfo.table_name + ")");
Cursor c5 = alc3.get(0);
indexInfo.isEmpty = true;
if (c5 != null) {
indexInfo.isEmpty = true;
ArrayList<String> emptytablecolumnnames = new ArrayList<String>();
c5.moveToFirst();
do {
emptytablecolumnnames.add(c5.getString(1));
} while (c5.moveToNext());
indexInfo.emptytablecolumnnames = emptytablecolumnnames;
}
}
//displays alert dialog from which use can update or delete a row
public void updateDeletePopup(int row) {
Cursor c2 = indexInfo.maincursor;
// a spinner which gives options to update or delete the row which user has selected
ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Click Here to Change this row");
spinnerArray.add("Update this row");
spinnerArray.add("Delete this row");
//create a layout with text values which has the column names and
//edit texts which has the values of the row which user has selected
final ArrayList<String> value_string = indexInfo.value_string;
final LinkedList<TextView> columnames = new LinkedList<TextView>();
final LinkedList<EditText> columvalues = new LinkedList<EditText>();
for (int i = 0; i < c2.getColumnCount(); i++) {
String cname = c2.getColumnName(i);
TextView tv = new TextView(getApplicationContext());
tv.setText(cname);
columnames.add(tv);
}
for (int i = 0; i < columnames.size(); i++) {
String cv = value_string.get(i);
EditText et = new EditText(getApplicationContext());
value_string.add(cv);
et.setText(cv);
columvalues.add(et);
}
int lastrid = 0;
// all text views , edit texts are added to this relative layout lp
final RelativeLayout lp = new RelativeLayout(AndroidDatabaseManager.this);
lp.setBackgroundColor(Color.WHITE);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.ALIGN_PARENT_TOP);
final ScrollView updaterowsv = new ScrollView(AndroidDatabaseManager.this);
LinearLayout lcrud = new LinearLayout(AndroidDatabaseManager.this);
LinearLayout.LayoutParams paramcrudtext = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
paramcrudtext.setMargins(0, 20, 0, 0);
//spinner which displays update , delete options
final Spinner crud_dropdown = new Spinner(getApplicationContext());
ArrayAdapter<String> crudadapter = new ArrayAdapter<String>(AndroidDatabaseManager.this,
android.R.layout.simple_spinner_item, spinnerArray) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setBackgroundColor(Color.WHITE);
TextView adap = (TextView) v;
adap.setTextSize(20);
return adap;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v = super.getDropDownView(position, convertView, parent);
v.setBackgroundColor(Color.WHITE);
return v;
}
};
crudadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crud_dropdown.setAdapter(crudadapter);
//lcrud.setId(299);
lcrud.addView(crud_dropdown, paramcrudtext);
RelativeLayout.LayoutParams rlcrudparam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlcrudparam.addRule(RelativeLayout.BELOW, lastrid);
lp.addView(lcrud, rlcrudparam);
for (int i = 0; i < columnames.size(); i++) {
TextView tv = columnames.get(i);
EditText et = columvalues.get(i);
int t = i + 100;
int k = i + 200;
int lid = i + 300;
tv.setId(t);
tv.setTextColor(Color.parseColor("#000000"));
et.setBackgroundColor(Color.parseColor("#F2F2F2"));
et.setTextColor(Color.parseColor("#000000"));
et.setId(k);
Log.d("text View Value", "" + tv.getText().toString());
final LinearLayout ll = new LinearLayout(AndroidDatabaseManager.this);
ll.setBackgroundColor(Color.parseColor("#FFFFFF"));
ll.setId(lid);
LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(0, 100);
lpp.weight = 1;
tv.setLayoutParams(lpp);
et.setLayoutParams(lpp);
ll.addView(tv);
ll.addView(et);
Log.d("Edit Text Value", "" + et.getText().toString());
RelativeLayout.LayoutParams rll = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rll.addRule(RelativeLayout.BELOW, ll.getId() - 1);
rll.setMargins(0, 20, 0, 0);
lastrid = ll.getId();
lp.addView(ll, rll);
}
updaterowsv.addView(lp);
//after the layout has been created display it in a alert dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isFinishing()) {
new AlertDialog.Builder(AndroidDatabaseManager.this)
.setTitle("values")
.setView(updaterowsv)
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
//this code will be executed when user changes values of edit text or spinner and clicks on ok button
public void onClick(DialogInterface dialog, int which) {
//get spinner value
String spinner_value = crud_dropdown.getSelectedItem().toString();
//it he spinner value is update this row get the values from
//edit text fields generate a update query and execute it
if (spinner_value.equalsIgnoreCase("Update this row")) {
indexInfo.index = 10;
String Query3 = "UPDATE " + indexInfo.table_name + " SET ";
for (int i = 0; i < columnames.size(); i++) {
TextView tvc = columnames.get(i);
EditText etc = columvalues.get(i);
if (!etc.getText().toString().equals("null")) {
Query3 = Query3 + tvc.getText().toString() + " = ";
if (i == columnames.size() - 1) {
Query3 = Query3 + "'" + etc.getText().toString() + "'";
} else {
Query3 = Query3 + "'" + etc.getText().toString() + "' , ";
}
}
}
Query3 = Query3 + " where ";
for (int i = 0; i < columnames.size(); i++) {
TextView tvc = columnames.get(i);
if (!value_string.get(i).equals("null")) {
Query3 = Query3 + tvc.getText().toString() + " = ";
if (i == columnames.size() - 1) {
Query3 = Query3 + "'" + value_string.get(i) + "' ";
} else {
Query3 = Query3 + "'" + value_string.get(i) + "' and ";
}
}
}
Log.d("Update Query", Query3);
//dbm.getData(Query3);
ArrayList<Cursor> aluc = dbm.getData(Query3);
Cursor tempc = aluc.get(1);
tempc.moveToLast();
Log.d("Update Mesage", tempc.getString(0));
if (tempc.getString(0).equalsIgnoreCase("Success")) {
tvmessage.setBackgroundColor(Color.parseColor("#2ecc71"));
tvmessage.setText(indexInfo.table_name + " table Updated Successfully");
refreshTable(0);
} else {
tvmessage.setBackgroundColor(Color.parseColor("#e74c3c"));
tvmessage.setText("Error:" + tempc.getString(0));
}
}
//it he spinner value is delete this row get the values from
//edit text fields generate a delete query and execute it
if (spinner_value.equalsIgnoreCase("Delete this row")) {
indexInfo.index = 10;
String Query5 = "DELETE FROM " + indexInfo.table_name + " WHERE ";
for (int i = 0; i < columnames.size(); i++) {
TextView tvc = columnames.get(i);
if (!value_string.get(i).equals("null")) {
Query5 = Query5 + tvc.getText().toString() + " = ";
if (i == columnames.size() - 1) {
Query5 = Query5 + "'" + value_string.get(i) + "' ";
} else {
Query5 = Query5 + "'" + value_string.get(i) + "' and ";
}
}
}
Log.d("Delete Query", Query5);
dbm.getData(Query5);
ArrayList<Cursor> aldc = dbm.getData(Query5);
Cursor tempc = aldc.get(1);
tempc.moveToLast();
Log.d("Update Mesage", tempc.getString(0));
if (tempc.getString(0).equalsIgnoreCase("Success")) {
tvmessage.setBackgroundColor(Color.parseColor("#2ecc71"));
tvmessage.setText("Row deleted from " + indexInfo.table_name + " table");
refreshTable(0);
} else {
tvmessage.setBackgroundColor(Color.parseColor("#e74c3c"));
tvmessage.setText("Error:" + tempc.getString(0));
}
}
}
})
.setNegativeButton("close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create().show();
}
}
});
}
public void refreshactivity() {
finish();
startActivity(getIntent());
}
public void refreshTable(int d) {
Cursor c3 = null;
tableLayout.removeAllViews();
if (d == 0) {
String Query8 = "select * from " + indexInfo.table_name;
ArrayList<Cursor> alc3 = dbm.getData(Query8);
c3 = alc3.get(0);
//saving cursor to the static indexinfo class which can be resued by the other functions
indexInfo.maincursor = c3;
}
if (d == 1) {
c3 = indexInfo.maincursor;
}
// if the cursor returened form tha database is not null we display the data in table layout
if (c3 != null) {
int counts = c3.getCount();
Log.d("counts", "" + counts);
tv.setText("" + counts);
TableRow tableheader = new TableRow(getApplicationContext());
tableheader.setBackgroundColor(Color.BLACK);
tableheader.setPadding(0, 2, 0, 2);
for (int k = 0; k < c3.getColumnCount(); k++) {
LinearLayout cell = new LinearLayout(AndroidDatabaseManager.this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(tableRowParams);
final TextView tableheadercolums = new TextView(getApplicationContext());
tableheadercolums.setPadding(0, 0, 4, 3);
tableheadercolums.setText("" + c3.getColumnName(k));
tableheadercolums.setTextColor(Color.parseColor("#000000"));
cell.addView(tableheadercolums);
tableheader.addView(cell);
}
tableLayout.addView(tableheader);
c3.moveToFirst();
//after displaying column names in the first row we display data in the remaining columns
//the below paginate table function will display the first 10 tuples of the tables
//the remaining tuples can be viewed by clicking on the next button
paginatetable(c3.getCount());
} else {
TableRow tableheader2 = new TableRow(getApplicationContext());
tableheader2.setBackgroundColor(Color.BLACK);
tableheader2.setPadding(0, 2, 0, 2);
LinearLayout cell = new LinearLayout(AndroidDatabaseManager.this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(tableRowParams);
final TextView tableheadercolums = new TextView(getApplicationContext());
tableheadercolums.setPadding(0, 0, 4, 3);
tableheadercolums.setText(" Table Is Empty ");
tableheadercolums.setTextSize(30);
tableheadercolums.setTextColor(Color.RED);
cell.addView(tableheadercolums);
tableheader2.addView(cell);
tableLayout.addView(tableheader2);
tv.setText("" + 0);
}
}
//the function which displays tuples from database in a table layout
public void paginatetable(final int number) {
final Cursor c3 = indexInfo.maincursor;
indexInfo.numberofpages = (c3.getCount() / 10) + 1;
indexInfo.currentpage = 1;
c3.moveToFirst();
int currentrow = 0;
//display the first 10 tuples of the table selected by user
do {
final TableRow tableRow = new TableRow(getApplicationContext());
tableRow.setBackgroundColor(Color.BLACK);
tableRow.setPadding(0, 2, 0, 2);
for (int j = 0; j < c3.getColumnCount(); j++) {
LinearLayout cell = new LinearLayout(this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(tableRowParams);
final TextView columsView = new TextView(getApplicationContext());
columsView.setText("" + c3.getString(j));
columsView.setTextColor(Color.parseColor("#000000"));
columsView.setPadding(0, 0, 4, 3);
cell.addView(columsView);
tableRow.addView(cell);
}
tableRow.setVisibility(View.VISIBLE);
currentrow = currentrow + 1;
//we create listener for each table row when clicked a alert dialog will be displayed
//from where user can update or delete the row
tableRow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final ArrayList<String> value_string = new ArrayList<String>();
for (int i = 0; i < c3.getColumnCount(); i++) {
LinearLayout llcolumn = (LinearLayout) tableRow.getChildAt(i);
TextView tc = (TextView) llcolumn.getChildAt(0);
String cv = tc.getText().toString();
value_string.add(cv);
}
indexInfo.value_string = value_string;
//the below function will display the alert dialog
updateDeletePopup(0);
}
});
tableLayout.addView(tableRow);
} while (c3.moveToNext() && currentrow < 10);
indexInfo.index = currentrow;
// when user clicks on the previous button update the table with the previous 10 tuples from the database
previous.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int tobestartindex = (indexInfo.currentpage - 2) * 10;
//if the tbale layout has the first 10 tuples then toast that this is the first page
if (indexInfo.currentpage == 1) {
Toast.makeText(getApplicationContext(), "This is the first page", Toast.LENGTH_LONG).show();
} else {
indexInfo.currentpage = indexInfo.currentpage - 1;
c3.moveToPosition(tobestartindex);
boolean decider = true;
for (int i = 1; i < tableLayout.getChildCount(); i++) {
TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
if (decider) {
tableRow.setVisibility(View.VISIBLE);
for (int j = 0; j < tableRow.getChildCount(); j++) {
LinearLayout llcolumn = (LinearLayout) tableRow.getChildAt(j);
TextView columsView = (TextView) llcolumn.getChildAt(0);
columsView.setText("" + c3.getString(j));
}
decider = !c3.isLast();
if (!c3.isLast()) {
c3.moveToNext();
}
} else {
tableRow.setVisibility(View.GONE);
}
}
indexInfo.index = tobestartindex;
Log.d("index =", "" + indexInfo.index);
}
}
});
// when user clicks on the next button update the table with the next 10 tuples from the database
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//if there are no tuples to be shown toast that this the last page
if (indexInfo.currentpage >= indexInfo.numberofpages) {
Toast.makeText(getApplicationContext(), "This is the last page", Toast.LENGTH_LONG).show();
} else {
indexInfo.currentpage = indexInfo.currentpage + 1;
boolean decider = true;
for (int i = 1; i < tableLayout.getChildCount(); i++) {
TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
if (decider) {
tableRow.setVisibility(View.VISIBLE);
for (int j = 0; j < tableRow.getChildCount(); j++) {
LinearLayout llcolumn = (LinearLayout) tableRow.getChildAt(j);
TextView columsView = (TextView) llcolumn.getChildAt(0);
columsView.setText("" + c3.getString(j));
}
decider = !c3.isLast();
if (!c3.isLast()) {
c3.moveToNext();
}
} else {
tableRow.setVisibility(View.GONE);
}
}
}
}
});
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/data/db/WeatherContract.java
|
Java
|
package com.zmb.sunshine.data.db;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Contains database and column names used for storing ewather data.
*/
public class WeatherContract {
/**
* We use these integer codes in our database to represent different
* weather conditions. These codes map to images that are displayed.
*/
public static enum WeatherId {
STORM(0),
LIGHT_RAIN(1),
RAIN(2),
SNOW(3),
FOG(4),
CLEAR(5),
LIGHT_CLOUDS(6),
CLOUDS(7);
public final int mValue;
private WeatherId(int value) {
mValue = value;
}
public static WeatherId fromInt(int value) {
switch (value) {
case 0: return STORM;
case 1: return LIGHT_RAIN;
case 2: return RAIN;
case 3: return SNOW;
case 4: return FOG;
case 5: return CLEAR;
case 6: return LIGHT_CLOUDS;
case 7: return CLOUDS;
default: throw new IllegalArgumentException();
}
}
}
/**
* A name for the content provider.
*/
public static final String CONTENT_AUTHORITY = "com.zmb.sunshine";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
// paths that we append to the base URI
public static final String PATH_WEATHER = "weather";
public static final String PATH_LOCATION = "location";
private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMdd");
/**
* Convert a {@link java.util.Date} into a string that's compatible
* with the way we store dates (yyyyMMdd).
* @param date the date to convert
* @return the date expressed as a string
*/
public static String convertDateToString(Date date) {
return sDateFormat.format(date);
}
public static Date convertStringToDate(String date) {
try {
return sDateFormat.parse(date);
} catch (ParseException e) {
return null;
}
}
/**
* Defines the contents of the weather table.
*/
public static final class WeatherEntry implements BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_WEATHER).build();
// MIME types that indicate whether we return multiple items (dir) or a single item
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + PATH_WEATHER;
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + PATH_WEATHER;
public static Uri buildWeatherUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static Uri buildWeatherLocation(String locationSetting) {
return CONTENT_URI.buildUpon().appendPath(locationSetting).build();
}
public static Uri buildWeatherLocationWithDate(String location, String date) {
return CONTENT_URI.buildUpon().appendPath(location).appendPath(date).build();
}
public static Uri buildWeatherLocationWithStartDate(String location, String date) {
return CONTENT_URI.buildUpon().appendPath(location)
.appendQueryParameter(COLUMN_DATETEXT, date).build();
}
public static Uri buildWeatherLocatinWithStartAndEndDate(String location, String start, String end) {
return CONTENT_URI.buildUpon().appendPath(location)
.appendQueryParameter(COLUMN_DATETEXT, start)
.appendQueryParameter(QUERY_PARAM_END_DATE, end).build();
}
public static String getLocationSettingFromUri(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getDateFromUri(Uri uri) {
return uri.getPathSegments().get(2);
}
public static String getStartDateFromUri(Uri uri) {
return uri.getQueryParameter(COLUMN_DATETEXT);
}
public static String getEndDateFromUri(Uri uri) {
return uri.getQueryParameter(QUERY_PARAM_END_DATE);
}
public static final String TABLE_NAME = "weather";
/**
* A foreign key into the location table.
*/
public static final String COLUMN_LOC_KEY = "location_id";
/**
* The date, stored as text of the form yyyyMMdd.
*/
public static final String COLUMN_DATETEXT = "date";
public static final String QUERY_PARAM_END_DATE = "end_date";
public static final String COLUMN_WEATHER_ID = "weather_id";
/**
* A short description of the weather conditions.
*/
public static final String COLUMN_SHORT_DESCRIPTION = "short_desc";
/**
* Temperature is stored in degrees Celsius.
*/
public static final String COLUMN_TEMPERATURE_HIGH = "max";
/**
* Temperature is stored in degrees Celsius.
*/
public static final String COLUMN_TEMPERATURE_LOW = "min";
public static final String COLUMN_HUMIDITY = "humidity";
/**
* Pressure is measured in units of hPa.
*/
public static final String COLUMN_PRESSURE = "pressure";
/**
* Wind speed is measured in meters per second.
*/
public static final String COLUMN_WIND_SPEED = "wind";
public static final String COLUMN_DEGREES = "degrees";
}
/**
* Defines the contents of the location table.
*/
public static final class LocationEntry implements BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_LOCATION).build();
// MIME types that indicate whether we return multiple items (dir) or a single item
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + PATH_LOCATION;
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + PATH_LOCATION;
public static Uri buildLocationUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static final String TABLE_NAME = "location";
/**
* The location setting that is sent as part of the weather query.
*/
public static final String COLUMN_LOCATION_SETTING = "location_setting";
/**
* Human-readable location string provided by the API.
*/
public static final String COLUMN_CITY_NAME = "city_name";
public static final String COLUMN_LATITUDE = "latitude";
public static final String COLUMN_LONGITUDE = "longitude";
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/data/db/WeatherDbHelper.java
|
Java
|
package com.zmb.sunshine.data.db;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.zmb.sunshine.data.db.WeatherContract.LocationEntry;
import com.zmb.sunshine.data.db.WeatherContract.WeatherEntry;
import java.util.ArrayList;
public class WeatherDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "weather.db";
// should be incremented if the schema is changed!
private static final int DATABASE_VERSION = 1;
public WeatherDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// create our SQLite database tables
sqLiteDatabase.execSQL(SQL_CREATE_LOCATION_TABLE);
sqLiteDatabase.execSQL(SQL_CREATE_WEATHER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
// this only gets called if we change the version of our database
// drop the tables and recreate them according to the new schema
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + LocationEntry.TABLE_NAME);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WeatherEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
/**
* The SQL code for creating our weather table.
*/
private static final String SQL_CREATE_WEATHER_TABLE = "CREATE TABLE " + WeatherEntry.TABLE_NAME +
" (" + WeatherEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
WeatherEntry.COLUMN_LOC_KEY + " INTEGER NOT NULL, " +
WeatherEntry.COLUMN_DATETEXT + " TEXT NOT NULL, " +
WeatherEntry.COLUMN_SHORT_DESCRIPTION + " TEXT NOT NULL, " +
WeatherEntry.COLUMN_WEATHER_ID + " INTEGER NOT NULL, " + // TODO might change when we support other sources
WeatherEntry.COLUMN_TEMPERATURE_HIGH + " REAL NOT NULL, " +
WeatherEntry.COLUMN_TEMPERATURE_LOW + " REAL NOT NULL, " +
WeatherEntry.COLUMN_HUMIDITY + " REAL, " +
WeatherEntry.COLUMN_PRESSURE + " REAL, " +
WeatherEntry.COLUMN_WIND_SPEED + " REAL, " +
WeatherEntry.COLUMN_DEGREES + " REAL, " +
// location column is foreign key into location table
" FOREIGN KEY (" + WeatherEntry.COLUMN_LOC_KEY + ") REFERENCES " +
LocationEntry.TABLE_NAME + " (" + LocationEntry._ID + "), " +
// ensure that we only store one weather entry per day per location
" UNIQUE (" + WeatherEntry.COLUMN_DATETEXT + ", " +
WeatherEntry.COLUMN_LOC_KEY + ") ON CONFLICT REPLACE);";
private static final String SQL_CREATE_LOCATION_TABLE = "CREATE TABLE " + LocationEntry.TABLE_NAME +
" (" + LocationEntry._ID + " INTEGER PRIMARY KEY," +
LocationEntry.COLUMN_LOCATION_SETTING + " TEXT UNIQUE NOT NULL, " +
LocationEntry.COLUMN_CITY_NAME + " TEXT NOT NULL, " +
LocationEntry.COLUMN_LATITUDE + " REAL NOT NULL, " +
LocationEntry.COLUMN_LONGITUDE + " REAL NOT NULL, " +
"UNIQUE (" + LocationEntry.COLUMN_LOCATION_SETTING + ") ON CONFLICT IGNORE" +
");";
public ArrayList<Cursor> getData(String Query){
//get writable database
SQLiteDatabase sqlDB = this.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add(null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0) {
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
} catch(SQLException sqlEx){
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
} catch(Exception ex){
Log.d("printing exception", ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/data/openweathermap/OpenWeatherMapParser.java
|
Java
|
package com.zmb.sunshine.data.openweathermap;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.zmb.sunshine.data.AWeatherDataParser;
import com.zmb.sunshine.data.WeatherParseException;
import com.zmb.sunshine.data.db.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Parses weather data received from Open Weather map.
*/
public class OpenWeatherMapParser extends AWeatherDataParser {
private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily";
private String mLocation;
@Override
public URL buildUrl(String locationSetting, int daysToFetch) throws MalformedURLException {
mLocation = locationSetting;
// we have to add ",USA" to the location setting or open weather map
// gets confused and looks outside the USA
locationSetting += ",USA";
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter("q", locationSetting)
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", String.valueOf(daysToFetch))
.build();
URL url = new URL(uri.toString());
return url;
}
@Override
public void parse(Context context, String data, int numberOfDays) throws WeatherParseException {
try {
JSONObject json = new JSONObject(data);
JSONObject city = json.getJSONObject("city");
String cityName = city.getString("name");
JSONObject location = city.getJSONObject("coord");
double lat = location.getDouble("lat");
double lon = location.getDouble("lon");
long rowId = addLocation(context, mLocation, cityName, lat, lon);
List<ContentValues> itemsToInsert = new ArrayList<ContentValues>();
JSONArray days = json.getJSONArray("list");
for (int i = 0; i < numberOfDays; ++i) {
ContentValues values = parseDay(days.getJSONObject(i), rowId);
itemsToInsert.add(values);
}
int rowsInserted = context.getContentResolver().bulkInsert(
WeatherContract.WeatherEntry.CONTENT_URI,
itemsToInsert.toArray(new ContentValues[itemsToInsert.size()]));
Log.d("OpenWeatherMap", "Inserted " + rowsInserted + " rows of weather data.");
} catch (JSONException e) {
throw new WeatherParseException(data, e);
}
}
private ContentValues parseDay(JSONObject day, long locationRowId) throws JSONException {
JSONObject temp = day.getJSONObject("temp");
final double min = temp.getDouble("min");
final double max = temp.getDouble("max");
final int humidity = day.getInt("humidity");
final double pressure = day.getDouble("pressure");
final double windSpeed = day.getDouble("speed");
final double windDir = day.getDouble("deg");
JSONObject weather = day.getJSONArray("weather").getJSONObject(0);
final String desc = weather.getString("main");
final int weatherId = weather.getInt("id");
// open weather map reports the date as a unix timestamp (seconds)
// convert it to milliseconds to convert to a Date object
long datetime = day.getLong("dt");
Date date = new Date(datetime * 1000);
ContentValues values = new ContentValues();
values.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId);
values.put(WeatherContract.WeatherEntry.COLUMN_DATETEXT,
WeatherContract.convertDateToString(date));
values.put(WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_HIGH, max);
values.put(WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_LOW, min);
values.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESCRIPTION, desc);
values.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, getWeatherId(weatherId));
values.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
values.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
values.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDir);
values.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
return values;
}
/**
* Convert a weather ID code from the OpenWeatherMap API
* into the code we use in the database.
* @param apiId
* @return
*/
private static int getWeatherId(int apiId) {
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (apiId >= 200 && apiId <= 232) {
return WeatherContract.WeatherId.STORM.mValue;
} else if (apiId >= 300 && apiId <= 321) {
return WeatherContract.WeatherId.LIGHT_RAIN.mValue;
} else if (apiId >= 500 && apiId <= 504) {
return WeatherContract.WeatherId.RAIN.mValue;
} else if (apiId == 511) {
return WeatherContract.WeatherId.RAIN.mValue;
} else if (apiId >= 520 && apiId <= 531) {
return WeatherContract.WeatherId.RAIN.mValue;
} else if (apiId >= 600 && apiId <= 622) {
return WeatherContract.WeatherId.SNOW.mValue;
} else if (apiId >= 701 && apiId <= 761) {
return WeatherContract.WeatherId.FOG.mValue;
} else if (apiId == 761 || apiId == 781) {
return WeatherContract.WeatherId.STORM.mValue;
} else if (apiId == 800) {
return WeatherContract.WeatherId.CLEAR.mValue;
} else if (apiId == 801) {
return WeatherContract.WeatherId.LIGHT_CLOUDS.mValue;
} else if (apiId >= 802 && apiId <= 804) {
return WeatherContract.WeatherId.CLOUDS.mValue;
}
return -1;
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/data/worldweatheronline/WorldWeatherOnlineParser.java
|
Java
|
package com.zmb.sunshine.data.worldweatheronline;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.zmb.sunshine.data.AWeatherDataParser;
import com.zmb.sunshine.data.WeatherParseException;
import com.zmb.sunshine.data.db.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class WorldWeatherOnlineParser extends AWeatherDataParser {
private static final String TAG = WorldWeatherOnlineParser.class.getSimpleName();
private static final String API_KEY = "6b7892a1b12aeb6feb3b8785d4f94";
private static final String BASE_URI = "https://api.worldweatheronline.com/free/v2/weather.ashx";
private static final int SNOW_AND_THUNDER = 395;
private static final int LIGHT_SNOW_AND_THUNDER = 392;
private static final int RAIN_AND_THUNDER = 389;
private static final int THUNDERY_OUTBREAKS = 200;
private static final int LIGHT_RAIN_AND_THUNDER = 386;
private static final int HEAVY_ICE_PELLETS = 377;
private static final int ICE_PELLETS = 350;
private static final int LIGHT_ICE_PELLETS = 374;
private static final int BLIZZARD = 230;
private static final int BLOWING_SNOW = 227;
private static final int PATCHY_HEAVY_SNOW = 335;
private static final int PATCHY_MODERATE_SNOW = 329;
private static final int PATCHY_LIGHT_SNOW = 323;
private static final int HEAVY_SNOW_SHOWERS = 338;
private static final int SNOW_SHOWERS = 371;
private static final int LIGHT_SNOW_SHOWERS = 368;
private static final int LIGHT_SNOW = 326;
private static final int MODERATE_SNOW = 332;
private static final int PATCHY_SNOW_NEARBY = 179;
private static final int LIGHT_SLEET = 317;
private static final int HEAVY_SLEET = 320;
private static final int SLEET_SHOWERS = 365;
private static final int PATCHY_SLEET = 182;
private static final int LIGHT_SLEET_SHOWERS = 362;
private static final int TORRENTIAL_RAIN = 359;
private static final int RAIN = 356;
private static final int HEAVY_RAIN = 308;
private static final int HEAVY_RAIN_AT_TIMES = 305;
private static final int MODERATE_RAIN = 302;
private static final int MODERATE_RAIN_AT_TIMES = 299;
private static final int LIGHT_RAIN_SHOWER = 353;
private static final int LIGHT_RAIN = 296;
private static final int PATCHY_LIGHT_RAIN = 293;
private static final int PATCHY_RAIN_NEARBY = 176;
private static final int FREEZING_RAIN = 314;
private static final int LIGHT_FREEZING_RAIN = 311;
private static final int LIGHT_DRIZZLE = 266;
private static final int PATCHY_LIGHT_DRIZZLE = 263;
private static final int HEAVY_FREEZING_DRIZZLE = 284;
private static final int FREEZING_DRIZZLE = 281;
private static final int PATCHY_FREEZING_DRIZZLE = 185;
private static final int MIST = 143;
private static final int OVERCAST = 122;
private static final int CLOUDY = 119;
private static final int PARTLY_CLOUDY = 116;
private static final int CLEAR = 113;
private static final int FREEZING_FOG = 260;
private static final int FOG = 248;
private String mLocation;
@Override
public URL buildUrl(String locationSetting, int daysToFetch) throws MalformedURLException {
mLocation = locationSetting;
Uri uri = Uri.parse(BASE_URI).buildUpon()
.appendQueryParameter("key", API_KEY)
.appendQueryParameter("format", "json")
.appendQueryParameter("q", locationSetting)
.appendQueryParameter("num_of_days", String.valueOf(daysToFetch))
.appendQueryParameter("cc", "no") // don't care about current conditions
.appendQueryParameter("includeLocation", "yes")
.build();
return new URL(uri.toString());
}
@Override
public void parse(Context c, String data, int numberOfDays) throws WeatherParseException {
try {
JSONObject root = new JSONObject(data).getJSONObject("data");
JSONObject area = (JSONObject) root.getJSONArray("nearest_area").get(0);
JSONObject areaName = (JSONObject) area.getJSONArray("areaName").get(0);
String cityName = areaName.getString("value");
double lat = area.getDouble("latitude");
double lon = area.getDouble("longitude");
long locationRowId = addLocation(c, mLocation, cityName, lat, lon);
JSONArray weather = root.getJSONArray("weather");
List<ContentValues> valuesToAdd = new ArrayList<>();
for (int i = 0; i < weather.length(); ++i) {
valuesToAdd.add(parseDay(weather.getJSONObject(i), locationRowId));
}
int rowsInserted = c.getContentResolver().bulkInsert(
WeatherContract.WeatherEntry.CONTENT_URI,
valuesToAdd.toArray(new ContentValues[valuesToAdd.size()]));
Log.d("WorldWeatherOnline", "Inserted " + rowsInserted + " rows of weather data.");
} catch (JSONException e) {
throw new WeatherParseException(data, e);
}
}
private ContentValues parseDay(JSONObject day, long locationRowId) throws JSONException {
final double min = day.getDouble("mintempC");
final double max = day.getDouble("maxtempC");
// date is in YYYY-mm-DD format, we just need to remove the -
// to be compatible with our database
String date = day.getString("date").replace("-", "");
Log.v(TAG,"For " + date + ", " + max + " / " + min);
JSONObject hourly = (JSONObject) day.getJSONArray("hourly").get(0);
int humidity = hourly.getInt("humidity");
int weatherCode = hourly.getInt("weatherCode");
double pressure = hourly.getDouble("pressure");
double windDir = hourly.getDouble("winddirDegree");
// convert kph to mps
double windSpeedKmph = hourly.getDouble("windspeedKmph");
double windSpeed = windSpeedKmph * 1000 / 3600;
JSONObject weatherDescription = (JSONObject) hourly.getJSONArray("weatherDesc").get(0);
String desc = weatherDescription.getString("value");
ContentValues values = new ContentValues();
values.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId);
values.put(WeatherContract.WeatherEntry.COLUMN_DATETEXT, date);
values.put(WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_HIGH, max);
values.put(WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_LOW, min);
values.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESCRIPTION, desc);
values.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, convertWeatherId(weatherCode));
values.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
values.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
values.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDir);
values.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
return values;
}
/**
* Convert API weather codes to common codes used in our database.
*
* http://www.worldweatheronline.com/feed/wwoConditionCodes.xml
*
* @param weatherId
* @return
*/
private static int convertWeatherId(int weatherId) {
switch (weatherId) {
case CLEAR:
return WeatherContract.WeatherId.CLEAR.mValue;
case CLOUDY:
case OVERCAST:
return WeatherContract.WeatherId.CLOUDS.mValue;
case PARTLY_CLOUDY:
return WeatherContract.WeatherId.LIGHT_CLOUDS.mValue;
case FOG:
case FREEZING_FOG:
return WeatherContract.WeatherId.FOG.mValue;
case THUNDERY_OUTBREAKS:
case LIGHT_RAIN_AND_THUNDER:
case LIGHT_SNOW_AND_THUNDER:
case RAIN_AND_THUNDER:
case SNOW_AND_THUNDER:
case HEAVY_ICE_PELLETS:
case ICE_PELLETS:
case LIGHT_ICE_PELLETS:
return WeatherContract.WeatherId.STORM.mValue;
case LIGHT_DRIZZLE:
case LIGHT_FREEZING_RAIN:
case LIGHT_RAIN_SHOWER:
case LIGHT_SLEET:
case LIGHT_SLEET_SHOWERS:
case PATCHY_LIGHT_RAIN:
case PATCHY_LIGHT_DRIZZLE:
case LIGHT_RAIN:
case PATCHY_RAIN_NEARBY:
case MIST:
return WeatherContract.WeatherId.LIGHT_RAIN.mValue;
case TORRENTIAL_RAIN:
case RAIN:
case FREEZING_RAIN:
case HEAVY_RAIN:
case HEAVY_RAIN_AT_TIMES:
case HEAVY_SLEET:
case SLEET_SHOWERS:
case PATCHY_SLEET:
case MODERATE_RAIN:
case MODERATE_RAIN_AT_TIMES:
case FREEZING_DRIZZLE:
case HEAVY_FREEZING_DRIZZLE:
case PATCHY_FREEZING_DRIZZLE:
return WeatherContract.WeatherId.RAIN.mValue;
case SNOW_SHOWERS:
case BLOWING_SNOW:
case LIGHT_SNOW:
case MODERATE_SNOW:
case PATCHY_HEAVY_SNOW:
case PATCHY_LIGHT_SNOW:
case PATCHY_MODERATE_SNOW:
case HEAVY_SNOW_SHOWERS:
case LIGHT_SNOW_SHOWERS:
case PATCHY_SNOW_NEARBY:
case BLIZZARD:
return WeatherContract.WeatherId.SNOW.mValue;
default: return -1;
}
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/sync/DummyAuthenticator.java
|
Java
|
package com.zmb.sunshine.sync;
import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.os.Bundle;
/**
* This authenticator doesn't do anything and only exists so that
* we can use the SyncAdapter framework.
*/
public class DummyAuthenticator extends AbstractAccountAuthenticator {
public DummyAuthenticator(Context context) {
super(context);
}
@Override
public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
throw new UnsupportedOperationException();
}
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response,
Account account, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle options) throws NetworkErrorException {
throw new UnsupportedOperationException();
}
@Override
public String getAuthTokenLabel(String authTokenType) {
throw new UnsupportedOperationException();
}
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle options) throws NetworkErrorException {
throw new UnsupportedOperationException();
}
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account,
String[] features) throws NetworkErrorException {
throw new UnsupportedOperationException();
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/sync/DummyAuthenticatorService.java
|
Java
|
package com.zmb.sunshine.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* A service that allows the SyncAdapter framework to interact with our
* {@link com.zmb.sunshine.sync.DummyAuthenticator}.
*/
public class DummyAuthenticatorService extends Service {
private DummyAuthenticator mAuthenticator;
@Override
public void onCreate() {
super.onCreate();
mAuthenticator = new DummyAuthenticator(this);
}
@Override
public IBinder onBind(Intent intent) {
return mAuthenticator.getIBinder();
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/sync/SunshineSyncAdapter.java
|
Java
|
package com.zmb.sunshine.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncRequest;
import android.content.SyncResult;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import com.zmb.sunshine.R;
import com.zmb.sunshine.Sunshine;
import com.zmb.sunshine.data.IWeatherDataParser;
import com.zmb.sunshine.data.db.WeatherContract;
import com.zmb.sunshine.data.openweathermap.OpenWeatherMapParser;
import com.zmb.sunshine.data.worldweatheronline.WorldWeatherOnlineParser;
import com.zmb.sunshine.widget.SunshineWidget;
import com.zmb.utils.IoUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = SunshineSyncAdapter.class.getSimpleName();
private static final int DAYS_TO_FETCH = 14;
public static final int SYNC_INTERVAL_SECONDS = 60 * 60 * 3;
public static final int SYNC_FLEXTIME = SYNC_INTERVAL_SECONDS / 3;
public SunshineSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
String location = Sunshine.getPreferredLocation(getContext());
HttpURLConnection connection = null;
IWeatherDataParser parser = getParser();
try {
removeOldWeatherData();
URL url = parser.buildUrl(location, DAYS_TO_FETCH);
Log.v(TAG, "Querying " + url.toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
String response = IoUtils.readAll(inputStream);
parser.parse(getContext(), response, DAYS_TO_FETCH);
// update any widgets with the new data
SunshineWidget.updateAllWidgets(getContext());
} catch (IOException e) {
Log.e(TAG, "Failed to fetch weather", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private IWeatherDataParser getParser() {
Context c = getContext();
String provider = PreferenceManager.getDefaultSharedPreferences(c)
.getString(c.getString(R.string.pref_weather_provider_key),
c.getString(R.string.pref_weather_provider_default));
if (provider.equals(c.getString(R.string.pref_weather_provider_openweathermap))) {
return new OpenWeatherMapParser();
} else {
return new WorldWeatherOnlineParser();
}
}
/**
* A helper to get the fake account used with the SyncAdapter.
* @param context
* @return
*/
static Account getSyncAccount(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account account = new Account(context.getString(R.string.app_name),
context.getString(R.string.sync_account_type));
// if we don't have a password associated with the account, then the account doesn't exist yet
if (accountManager.getPassword(account) == null) {
// create the account (empty password and no user data)
if (!accountManager.addAccountExplicitly(account, "", null)) {
return null;
}
onAccountCreated(account, context);
}
return account;
}
static void configurePeriodicSync(Context context, int intervalSeconds, int flexTime) {
Account acct = getSyncAccount(context);
String authority = context.getString(R.string.content_authority);
Bundle extras = new Bundle();
// in kitkat (API 19) and up, we can use inexact repeating alarms
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
SyncRequest request = new SyncRequest.Builder()
.setExtras(extras) // shouldn't have to do this - Android 5.0 bug
.syncPeriodic(intervalSeconds, flexTime)
.setSyncAdapter(acct, authority).build();
ContentResolver.requestSync(request);
} else {
ContentResolver.addPeriodicSync(acct, authority, extras, intervalSeconds);
}
}
public static void initialize(Context context) {
// just make sure that an account has been created
getSyncAccount(context);
}
/**
* A helper method to start a sync immediately.
* @param context used to access the account service
*/
public static void syncNow(Context context) {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(getSyncAccount(context),
context.getString(R.string.content_authority), bundle);
}
/**
* Initial setup that we run when an acount is created.
* @param newAccount
* @param context
*/
private static void onAccountCreated(Account newAccount, Context context) {
SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL_SECONDS, SYNC_FLEXTIME);
ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);
}
private void removeOldWeatherData() {
String today = WeatherContract.convertDateToString(new Date());
String where = WeatherContract.WeatherEntry.COLUMN_DATETEXT + " < ?";
getContext().getContentResolver().delete(
WeatherContract.WeatherEntry.CONTENT_URI, where, new String[] { today });
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/sync/SunshineSyncService.java
|
Java
|
package com.zmb.sunshine.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class SunshineSyncService extends Service {
private static final Object sLock = new Object();
private static SunshineSyncAdapter sSyncAdapter;
@Override
public void onCreate() {
super.onCreate();
synchronized (sLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SunshineSyncAdapter(getApplicationContext(), true);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/sunshine/widget/SunshineWidget.java
|
Java
|
package com.zmb.sunshine.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import com.zmb.sunshine.MainActivity;
import com.zmb.sunshine.R;
import com.zmb.sunshine.Sunshine;
import com.zmb.sunshine.data.db.WeatherContract;
import java.util.Calendar;
import java.util.Date;
/**
* Implementation of App Widget functionality.
*/
public class SunshineWidget extends AppWidgetProvider {
// TODO: background color from wallpaper ??
private static final String TAG = "Widget";
private static final String[] COLUMNS = {
WeatherContract.WeatherEntry.COLUMN_DATETEXT,
WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_HIGH,
WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_LOW,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID
};
private static final int COL_DATE = 0;
private static final int COL_HIGH = 1;
private static final int COL_LOW = 2;
private static final int COL_WEATHER_ID = 3;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
boolean isMetric = Sunshine.isMetric(context);
// There may be multiple widgets active, so update all of them
for (int i = 0; i < appWidgetIds.length; ++i) {
updateAppWidget(context, appWidgetManager, appWidgetIds[i], isMetric);
}
}
/**
* Called when the widget is first placed and any time it is resized.
* @param context
* @param appWidgetManager
* @param appWidgetId
* @param newOptions
*/
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager,
int appWidgetId, Bundle newOptions) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
Log.v(TAG, "App Widget Options Changed");
// TODO: customize how many days we display based on the size
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
Log.v(TAG, "App widget enabled");
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
Log.v(TAG, "App widget disabled");
}
/**
* Utility method for forcing an update of all Sunshine widgets.
* @param context
*/
public static void updateAllWidgets(Context context) {
updateAllWidgets(context, Sunshine.isMetric(context));
}
public static void updateAllWidgets(Context context, boolean isMetric) {
Log.v(TAG, "Forcing widget update");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName component = new ComponentName(context.getApplicationContext(), SunshineWidget.class);
for (int id : manager.getAppWidgetIds(component)) {
updateAppWidget(context, manager, id, isMetric);
}
}
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId, boolean isMetric) {
Date todaysDate = new Date();
String today = WeatherContract.convertDateToString(todaysDate);
// we only want to query for 3 days of data
Calendar calendar = Calendar.getInstance();
calendar.setTime(todaysDate);
calendar.add(Calendar.DATE, 3);
Date endDate = calendar.getTime();
String end = WeatherContract.convertDateToString(endDate);
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATETEXT + " ASC";
Uri uri = WeatherContract.WeatherEntry.buildWeatherLocatinWithStartAndEndDate(
Sunshine.getPreferredLocation(context), today, end);
// TODO: we might want to do the query in the background
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(uri, COLUMNS, null, null, sortOrder);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.sunshine_widget);
// clicking the widget should open the sunshine App
Intent startApp = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, startApp, 0);
views.setOnClickPendingIntent(R.id.widget_main_layout, pendingIntent);
try {
// update views - just brute force each of 3 days
if (cursor.moveToFirst()) {
Log.v(TAG, "A");
String temperature = Sunshine.formatTemperature(context, cursor.getDouble(COL_HIGH), isMetric) +
" / " + Sunshine.formatTemperature(context, cursor.getDouble(COL_LOW), isMetric);
views.setTextViewText(R.id.widget_day_text0, Sunshine.shortFriendlyDate(context, cursor.getString(COL_DATE)));
views.setTextViewText(R.id.widget_temperature_text0, temperature);
views.setImageViewResource(R.id.widget_icon0, Sunshine.getIconForWeatherId(
WeatherContract.WeatherId.fromInt(cursor.getInt(COL_WEATHER_ID))));
}
if (cursor.moveToNext()) {
Log.v(TAG, "B");
String temperature = Sunshine.formatTemperature(context, cursor.getDouble(COL_HIGH), isMetric) +
" / " + Sunshine.formatTemperature(context, cursor.getDouble(COL_LOW), isMetric);
views.setTextViewText(R.id.widget_day_text1, Sunshine.shortFriendlyDate(context, cursor.getString(COL_DATE)));
views.setTextViewText(R.id.widget_temperature_text1, temperature);
views.setImageViewResource(R.id.widget_icon1, Sunshine.getIconForWeatherId(
WeatherContract.WeatherId.fromInt(cursor.getInt(COL_WEATHER_ID))));
}
if (cursor.moveToNext()) {
Log.v(TAG, "C");
String temperature = Sunshine.formatTemperature(context, cursor.getDouble(COL_HIGH), isMetric) +
" / " + Sunshine.formatTemperature(context, cursor.getDouble(COL_LOW), isMetric);
views.setTextViewText(R.id.widget_day_text2, Sunshine.shortFriendlyDate(context, cursor.getString(COL_DATE)));
views.setTextViewText(R.id.widget_temperature_text2, temperature);
views.setImageViewResource(R.id.widget_icon2, Sunshine.getIconForWeatherId(
WeatherContract.WeatherId.fromInt(cursor.getInt(COL_WEATHER_ID))));
}
} finally {
cursor.close();
}
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
app/src/main/java/com/zmb/utils/IoUtils.java
|
Java
|
package com.zmb.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by zberg_000 on 8/9/2014.
*/
public class IoUtils {
private IoUtils() { }
/**
* Reads all input from an input stream.
* Closes the stream when done.
* @param input
* @return
* @throws IOException
*/
public static String readAll(InputStream input) throws IOException {
try {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// readLine() consumes the newline, so we restore it here
buffer.append(line).append("\n");
}
return buffer.toString();
} finally {
input.close();
}
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
build.gradle
|
Gradle
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.+'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
settings.gradle
|
Gradle
|
include ':app'
|
zmb3/sunshine
| 1
|
Sample weather app for Android
|
Java
|
zmb3
|
Zac Bergquist
|
gravitational
|
rollup.config.js
|
JavaScript
|
import typescript from '@rollup/plugin-typescript'
export default [
{
input: 'packages/jsx/src/index.ts',
output: [
{
format: 'esm',
file: 'packages/jsx/lib/index.js',
},
],
plugins: [typescript({ tsconfig: 'packages/jsx/tsconfig.json' })],
},
]
|
znck/vue-jsx-prototype
| 2
|
Prototype for improving JSX types
|
TypeScript
|
znck
|
Rahul Kadyan
|
grammarly
|
client.js
|
JavaScript
|
import { isEmpty, last } from "meteor/ddp-common/utils.js";
let queueSize = 0;
let queue = Promise.resolve();
function queueFunction(fn) {
queueSize += 1;
let resolve;
let reject;
let promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
queue = queue.finally(() => {
fn(resolve, reject);
return promise;
});
promise.finally(() => {
queueSize -= 1;
if (queueSize === 0) {
Meteor.connection._maybeMigrate();
}
});
return promise;
}
let oldReadyToMigrate = Meteor.connection._readyToMigrate;
Meteor.connection._readyToMigrate = function () {
if (queueSize > 0) {
return false;
}
return oldReadyToMigrate.apply(this, arguments);
}
let currentMethodInvocation = null;
/**
* Meteor sets CurrentMethodInvocation to undefined for the reasons explained at
* https://github.com/meteor/meteor/blob/c9e3551b9673a7ed607f18cb1128563ff49ca96f/packages/ddp-client/common/livedata_connection.js#L578-L605
* The app code could call `.then` on a promise while the async stub is running,
* causing the `then` callback to think it is inside the stub.
*
* With the queueing we are doing, this is no longer necessary. The point
* of the queueing is to prevent app/package code from running while
* the stub is running, so we don't need to worry about this.
*/
let oldCallAsync = Meteor.connection.callAsync;
Meteor.connection.callAsync = function () {
currentMethodInvocation = DDP._CurrentMethodInvocation.get();
return oldCallAsync.apply(this, arguments);
}
let oldApplyAsync = Meteor.connection.applyAsync;
Meteor.connection.applyAsync = function () {
let args = arguments;
let name = args[0];
if (currentMethodInvocation) {
DDP._CurrentMethodInvocation._set(currentMethodInvocation);
currentMethodInvocation = null;
}
const enclosing = DDP._CurrentMethodInvocation.get();
const alreadyInSimulation = enclosing?.isSimulation;
const isFromCallAsync = enclosing?._isFromCallAsync;
if (Meteor.connection._getIsSimulation({
isFromCallAsync, alreadyInSimulation
})) {
// In stub - call immediately
return oldApplyAsync.apply(this, args);
}
return queueFunction((resolve, reject) => {
let finished = false;
Meteor._setImmediate(() => {
oldApplyAsync.apply(this, args).then((result) => {
finished = true;
resolve(result);
}, (err) => {
finished = true;
reject(err);
});
});
Meteor._setImmediate(() => {
if (!finished) {
console.warn(`Method stub (${name}) took too long and could cause unexpected problems. Learn more at https://github.com/zodern/fix-async-stubs/#limitations`);
}
});
});
};
let oldApply = Meteor.connection.apply;
Meteor.connection.apply = function () {
// [name, args, options]
let options = arguments[2] || {};
let wait = options.wait;
// Apply runs the stub before synchronously returning.
//
// However, we want the server to run the methods in the original call order
// so we have to queue sending the message to the server until any previous async
// methods run.
// This does mean the stubs run in a different order than the methods on the
// server.
// TODO: can we queue Meteor.apply in some situations instead of running
// immediately?
let oldOutstandingMethodBlocks = Meteor.connection._outstandingMethodBlocks;
// Meteor only sends the method if _outstandingMethodBlocks.length is 1.
// Add a wait block to force Meteor to put the new method in a second block.
let outstandingMethodBlocks = [{ wait: true, methods: [] }];
Meteor.connection._outstandingMethodBlocks = outstandingMethodBlocks;
let result;
try {
result = oldApply.apply(this, arguments);
} finally {
Meteor.connection._outstandingMethodBlocks = oldOutstandingMethodBlocks;
}
if (outstandingMethodBlocks[1]) {
let methodInvoker = outstandingMethodBlocks[1].methods[0];
if (methodInvoker) {
queueMethodInvoker(methodInvoker, wait);
}
}
return result;
};
function queueMethodInvoker(methodInvoker, wait) {
queueFunction((resolve) => {
let self = Meteor.connection;
// based on https://github.com/meteor/meteor/blob/e0631738f2a8a914d8a50b1060e8f40cb0873680/packages/ddp-client/common/livedata_connection.js#L833-L853C1
if (wait) {
// It's a wait method! Wait methods go in their own block.
self._outstandingMethodBlocks.push({
wait: true,
methods: [methodInvoker]
});
} else {
// Not a wait method. Start a new block if the previous block was a wait
// block, and add it to the last block of methods.
if (isEmpty(self._outstandingMethodBlocks) ||
last(self._outstandingMethodBlocks).wait) {
self._outstandingMethodBlocks.push({
wait: false,
methods: [],
});
}
last(self._outstandingMethodBlocks).methods.push(methodInvoker);
}
// If we added it to the first block, send it out now.
if (self._outstandingMethodBlocks.length === 1) methodInvoker.sendMessage();
resolve();
});
}
let queueSend = false;
let oldSubscribe = Meteor.connection.subscribe;
Meteor.connection.subscribe = function () {
queueSend = true;
try {
return oldSubscribe.apply(this, arguments);
} finally {
queueSend = false;
}
};
let oldSend = Meteor.connection._send;
Meteor.connection._send = function () {
if (!queueSend) {
return oldSend.apply(this, arguments);
}
queueSend = false;
queueFunction((resolve) => {
try {
oldSend.apply(this, arguments);
} finally {
resolve();
}
});
};
// Re-create these proxied functions to use our wrapper
[
'callAsync',
'apply',
'applyAsync',
'subscribe'
].forEach(name => {
Meteor[name] = Meteor.connection[name].bind(Meteor.connection);
});
|
zodern/fix-async-stubs
| 3
|
Package to remove limitations with async stubs in Meteor
|
JavaScript
|
zodern
| ||
package.js
|
JavaScript
|
Package.describe({
name: 'zodern:fix-async-stubs',
version: '1.0.2',
summary: 'Fixes issues with async method stubs',
git: 'https://github.com/zodern/fix-async-stubs.git',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('2.13.3');
api.use('ecmascript');
api.use('ddp-client');
api.mainModule('client.js', 'client');
});
Package.onTest(function(api) {
api.use('ecmascript');
api.use('tinytest');
api.use('zodern:fix-async-stubs');
api.addFiles('tests/server-setup.js', 'server');
api.addFiles('tests/client.js', 'client');
});
|
zodern/fix-async-stubs
| 3
|
Package to remove limitations with async stubs in Meteor
|
JavaScript
|
zodern
| ||
tests/client.js
|
JavaScript
|
import { Tinytest } from "meteor/tinytest";
let events = [];
Meteor.methods({
'sync-stub'() {
events.push('sync-stub');
return 'sync-stub-result'
},
async 'async-stub'() {
events.push('start async-stub');
await 0;
events.push('end async-stub');
return 'async-stub-result'
},
callAsyncFromSyncStub() {
events.push('callAsyncFromSyncStub');
Meteor.callAsync('async-stub');
},
async callSyncStubFromAsyncStub() {
events.push('start callSyncStubFromAsyncStub');
await 0
let result = Meteor.call('sync-stub');
events.push('end callSyncStubFromAsyncStub');
return result;
},
callSyncStubFromSyncStub() {
events.push('callSyncStubFromSyncStub');
return Meteor.call('sync-stub');
},
callAsyncStubFromAsyncStub() {
events.push('callAsyncStubFromAsyncStub');
return Meteor.callAsync('async-stub');
}
});
Tinytest.addAsync('applyAsync - server only', async function (test) {
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let stubResult = await Meteor.applyAsync('server-only-sync', [], { returnStubValue: true }, (err, result) => {
console.log(err);
if (!err) {
serverResolver(result);
}
});
let serverResult = await serverPromise;
test.equal(stubResult, undefined);
test.equal(serverResult, 'sync-result');
});
Tinytest.addAsync('applyAsync - sync stub', async function (test) {
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let stubResult = await Meteor.applyAsync('sync-stub', [], {
returnStubValue: true
}, (err, result) => {
console.log(err);
if (!err) {
serverResolver(result);
}
});
let serverResult = await serverPromise;
test.equal(stubResult, 'sync-stub-result');
test.equal(serverResult, 'sync-server-result');
});
Tinytest.addAsync('applyAsync - callAsync', async function (test) {
let serverResult = await Meteor.callAsync('async-stub');
test.equal(serverResult, 'async-server-result');
});
Tinytest.addAsync('applyAsync - callAsync twice', async function (test) {
events = [];
let promise1 = Meteor.callAsync('async-stub');
let promise2 = Meteor.callAsync('async-stub');
let results = await Promise.all([promise1, promise2]);
test.equal(events, ['start async-stub', 'end async-stub', 'start async-stub', 'end async-stub']);
test.equal(results, ['async-server-result', 'async-server-result']);
});
// Broken in Meteor 2.13: https://github.com/meteor/meteor/issues/12889#issue-1998128607
Tinytest.addAsync('applyAsync - callAsync from async stub', async function (test) {
await Meteor.callAsync('getAndResetEvents');
events = [];
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let stubResult = await Meteor.applyAsync('callAsyncStubFromAsyncStub', [], { returnStubValue: true }, (err, result) => {
if (!err) {
serverResolver(result);
}
});
let serverResult = await serverPromise;
let serverEvents = await Meteor.callAsync('getAndResetEvents');
test.equal(stubResult, 'async-stub-result');
test.equal(serverResult, 'server result');
test.equal(events, ['callAsyncStubFromAsyncStub', 'start async-stub', 'end async-stub']);
test.equal(serverEvents, ['callAsyncStubFromAsyncStub']);
});
Tinytest.addAsync('applyAsync - callAsync in then', async function (test) {
await Meteor.callAsync('getAndResetEvents');
events = [];
let result = await Meteor.callAsync('async-stub').then(() => Meteor.callAsync('async-stub'));
let serverEvents = await Meteor.callAsync('getAndResetEvents');
test.equal(events, ['start async-stub', 'end async-stub', 'start async-stub', 'end async-stub']);
test.equal(serverEvents, ['async-stub', 'async-stub']);
test.equal(result, 'async-server-result');
});
Tinytest.addAsync('applyAsync - call from async stub', async function (test) {
await Meteor.callAsync('getAndResetEvents');
events = [];
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let stubResult = await Meteor.applyAsync('callSyncStubFromAsyncStub', [], { returnStubValue: true }, (err, result) => {
if (!err) {
serverResolver(result);
}
});
let serverResult = await serverPromise;
let serverEvents = await Meteor.callAsync('getAndResetEvents');
test.equal(stubResult, 'sync-stub-result');
test.equal(serverResult, 'server result');
test.equal(events, ['start callSyncStubFromAsyncStub', 'sync-stub', 'end callSyncStubFromAsyncStub']);
test.equal(serverEvents, ['callSyncStubFromAsyncStub']);
});
Tinytest.addAsync('apply - call from sync stub', async function (test) {
await Meteor.callAsync('getAndResetEvents');
events = [];
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let stubResult = Meteor.apply('callSyncStubFromSyncStub', [], { returnStubValue: true }, (err, result) => {
if (!err) {
serverResolver(result);
}
});
let serverResult = await serverPromise;
let serverEvents = await Meteor.callAsync('getAndResetEvents');
test.equal(stubResult, 'sync-stub-result');
test.equal(serverResult, 'server result');
test.equal(events, ['callSyncStubFromSyncStub', 'sync-stub']);
test.equal(serverEvents, ['callSyncStubFromSyncStub']);
});
Tinytest.addAsync('apply - proper order with applyAsync', async function (test) {
await Meteor.callAsync('getAndResetEvents');
events = [];
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let promise1 = Meteor.callAsync('callSyncStubFromAsyncStub');
let stubResult = Meteor.apply('callSyncStubFromSyncStub', [], { returnStubValue: true }, (err, result) => {
if (!err) {
serverResolver(result);
}
});
let promise2 = Meteor.callAsync('server-only-sync');
let [
serverResult,
result1,
result2
] = await Promise.all([serverPromise, promise1, promise2]);
let serverEvents = await Meteor.callAsync('getAndResetEvents');
test.equal(stubResult, 'sync-stub-result');
test.equal(serverResult, 'server result');
test.equal(result1, 'server result');
test.equal(result2, 'sync-result');
test.equal(events, ['callSyncStubFromSyncStub', 'sync-stub', 'start callSyncStubFromAsyncStub', 'sync-stub', 'end callSyncStubFromAsyncStub']);
test.equal(serverEvents, ['callSyncStubFromAsyncStub', 'callSyncStubFromSyncStub', 'server-only-sync']);
});
Tinytest.addAsync('apply - wait', async function (test) {
await Meteor.callAsync('getAndResetEvents');
events = [];
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let stubResult = Meteor.apply(
'callSyncStubFromSyncStub',
[],
{ returnStubValue: true, wait: true },
(err, result) => {
if (!err) {
serverResolver(result);
}
});
const serverResult = await serverPromise;
test.equal(stubResult, 'sync-stub-result');
test.equal(serverResult, 'server result');
});
Tinytest.addAsync('apply - preserve order with subscriptions', async function (test) {
await Meteor.callAsync('getAndResetEvents');
let serverResolver;
let serverPromise = new Promise((resolve) => {
serverResolver = resolve;
});
let subResolver;
let subPromise = new Promise((resolve) => {
subResolver = resolve;
});
Meteor.call('server-only-sync', (err, result) => {
if (!err) {
serverResolver(result);
}
});
let handle = Meteor.subscribe('simple-publication', () => subResolver());
await serverPromise;
await subPromise;
handle.stop();
let serverEvents = await Meteor.callAsync('getAndResetEvents');
test.equal(serverEvents, ['server-only-sync', 'publication']);
});
|
zodern/fix-async-stubs
| 3
|
Package to remove limitations with async stubs in Meteor
|
JavaScript
|
zodern
| ||
tests/server-setup.js
|
JavaScript
|
let events = [];
Meteor.publish('simple-publication', function () {
events.push('publication');
this.ready();
});
Meteor.methods({
getAndResetEvents() {
let oldEvents = events;
events = [];
return oldEvents;
},
'server-only-sync' () {
events.push('server-only-sync');
return 'sync-result';
},
async 'server-only-async' () {
events.push('server-only-async');
await 0
return 'server-only-async-result';
},
echo(message) {
events.push('echo');
return message;
},
'sync-stub' () {
events.push('sync-stub');
return 'sync-server-result'
},
'async-stub' () {
events.push('async-stub');
return 'async-server-result'
},
'callAsyncFromSyncStub'() {
events.push('callAsyncFromSyncStub');
},
'callSyncStubFromAsyncStub'() {
events.push('callSyncStubFromAsyncStub');
return 'server result';
},
'callSyncStubFromSyncStub'() {
events.push('callSyncStubFromSyncStub');
return 'server result';
},
'callAsyncStubFromAsyncStub'() {
events.push('callAsyncStubFromAsyncStub');
return 'server result';
}
});
|
zodern/fix-async-stubs
| 3
|
Package to remove limitations with async stubs in Meteor
|
JavaScript
|
zodern
| ||
hmr-runtime.js
|
JavaScript
|
const { makeApplyHmr } = require('meteor/zodern:melte-compiler/hmr-runtime.js');
module.exports.applyHmr = makeApplyHmr(args => {
// Mark this file as reloadable
args.m.hot.accept();
let acceptCallback = null;
if (args.m.hot.data?.acceptCallback) {
// svelte-hmr expects accept to work as with nollup or vite
// applying changes is done synchronously, so we wait until after it is done
setTimeout(() => args.m.hot.data.acceptCallback(), 10);
}
args.m.hot.dispose((data) => {
if (acceptCallback) {
data.acceptCallback = acceptCallback;
}
});
return Object.assign({}, args, {
hot: {
...args.m.hot,
accept(cb) {
acceptCallback = cb;
}
},
hotOptions: {
...(args.hotOptions || {}),
noOverlay: true
},
reload() {
if (Package && Package.reload) {
Package.reload.Reload._reload({ immediateMigration: true });
} else {
window.location.reload();
}
}
});
});
|
zodern/melte
| 34
|
Svelte compiler for Meteor with built in tracker integration and HMR
|
JavaScript
|
zodern
| ||
package.js
|
JavaScript
|
Package.describe({
name: 'zodern:melte',
version: '1.7.4',
summary: 'Svelte compiler with tracker integration, HMR and Typescript support',
git: 'https://github.com/zodern/melte.git',
documentation: 'README.md'
});
Package.registerBuildPlugin({
name: 'melte-compiler',
use: [
'ecmascript@0.12.7',
'zodern:melte-compiler@1.4.3'
],
sources: [
'plugin.js'
],
npmDependencies: {
'@babel/runtime': '7.4.3',
}
});
Package.onUse(function (api) {
api.versionsFrom('1.8.1');
api.use('isobuild:compiler-plugin@1.0.0');
api.use('ecmascript@0.12.7', 'client');
api.use('tracker', 'client');
api.use('zodern:melte-compiler', 'client');
api.addFiles('tracker.js', 'client');
// Dependencies for compiled Svelte components (taken from `ecmascript`).
api.imply([
'ecmascript-runtime',
'babel-runtime',
'promise@0.11.2||1.0.0-beta.300-6'
]);
});
|
zodern/melte
| 34
|
Svelte compiler for Meteor with built in tracker integration and HMR
|
JavaScript
|
zodern
| ||
plugin.js
|
JavaScript
|
import MelteCompiler from 'meteor/zodern:melte-compiler/MelteCompiler.js';
import options from 'meteor/zodern:melte-compiler/options.js';
Plugin.registerCompiler({
extensions: (options && options.extensions) || ['svelte']
}, () => new MelteCompiler(options));
|
zodern/melte
| 34
|
Svelte compiler for Meteor with built in tracker integration and HMR
|
JavaScript
|
zodern
| ||
proxy-adapter.js
|
JavaScript
|
if (process.env.NODE_ENV === "development") {
const { proxyAdapter } = require('meteor/zodern:melte-compiler/hmr-runtime.js');
module.exports = proxyAdapter;
}
|
zodern/melte
| 34
|
Svelte compiler for Meteor with built in tracker integration and HMR
|
JavaScript
|
zodern
| ||
tracker.js
|
JavaScript
|
const { onDestroy } = require('svelte');
const { Tracker } = require('meteor/tracker');
module.exports = {
createReactiveWrapper() {
let computation = null;
onDestroy(() => {
if (computation) {
computation.stop();
}
});
return function (func) {
if (computation) {
computation.stop();
}
computation = Tracker.autorun(func);
return computation;
}
}
}
|
zodern/melte
| 34
|
Svelte compiler for Meteor with built in tracker integration and HMR
|
JavaScript
|
zodern
| ||
package.js
|
JavaScript
|
Package.describe({
name: 'zodern:build-profiler',
version: '1.1.0',
summary: 'Profile the Meteor build process',
git: 'https://github.com/zodern/meteor-build-profiler.git',
documentation: 'README.md'
});
Package.registerBuildPlugin({
name: "zodern:build-profiler",
sources: [
'profile.js',
'plugin.js',
],
npmDependencies: {
'v8-profiler-next': "1.4.2",
}
});
Package.onUse(function (api) {
});
|
zodern/meteor-build-profiler
| 5
|
JavaScript
|
zodern
| |||
plugin.js
|
JavaScript
|
var fs = Npm.require('fs');
var path = Npm.require('path');
var meteorLocalPath = path.resolve(process.cwd(), '.meteor/local');
var profilesPath = path.resolve(meteorLocalPath, 'cpu-profiles');
// There are some situations where the package could be loaded outside of a Meteor app,
// such as when running `meteor test-packages`
var inApp = fs.existsSync(meteorLocalPath);
var patchedSymbol = Symbol('build-profile-patch');
if (inApp) {
try {
fs.mkdirSync(profilesPath);
} catch (e) {
if (e.code !== 'EEXIST') {
console.log(e);
}
}
var mainModule = global.process.mainModule;
var absPath = mainModule.filename.split(path.sep).slice(0, -1).join(path.sep);
var require = function (filePath) {
return mainModule.require(path.resolve(absPath, filePath));
};
var AppRunner = require('./runners/run-app.js').AppRunner;
var v8Profiler = Npm.require('v8-profiler-next');
var Profiler = getProfiler(v8Profiler, fs);
if (!AppRunner[patchedSymbol]) {
AppRunner[patchedSymbol] = true;
var oldMakePromise = AppRunner.prototype._makePromise;
AppRunner.prototype._makePromise = function (name) {
if (name === 'run') {
Profiler.stopProfile('client-rebuild');
}
return oldMakePromise.apply(this, arguments);
};
var oldResolvePromise = AppRunner.prototype._resolvePromise;
AppRunner.prototype._resolvePromise = function (name, value) {
var outcome = value ? value.outcome : '';
if (name === 'run' && outcome === 'changed') {
Profiler.startProfile('full-rebuild', {
exportPath: path.join(profilesPath, 'full-rebuild.cpuprofile'),
});
}
if (name === 'run' && outcome === 'changed-refreshable') {
Profiler.startProfile('client-rebuild', {
exportPath: path.join(profilesPath, 'client-rebuild.cpuprofile'),
});
}
else if (name === 'start') {
Profiler.stopProfile('initial-build');
Profiler.stopProfile('full-rebuild');
}
return oldResolvePromise.apply(this, arguments);
};
Profiler.startProfile('initial-build', {
exportPath: path.join(profilesPath, 'initial-build.cpuprofile'),
});
}
}
|
zodern/meteor-build-profiler
| 5
|
JavaScript
|
zodern
| |||
profile.js
|
JavaScript
|
getProfiler = function (v8Profiler, fs) {
var currentProfiles = {};
function colorize(s) {
return '\x1b[36m' + s + '\x1b[0m';
};
var startProfile = function (profileName, options) {
if (currentProfiles[profileName]) {
return;
}
currentProfiles[profileName] = options;
console.log('');
console.log(colorize('Profiling "' + profileName + '"'));
v8Profiler.startProfiling(profileName);
};
var stopProfile = function (profileName) {
if (!currentProfiles[profileName] || currentProfiles[profileName].complete) {
return;
}
currentProfiles[profileName].complete = true;
var profile = v8Profiler.stopProfiling(profileName);
var exportPath = currentProfiles[profileName].exportPath;
profile.export(function (error, result) {
fs.writeFileSync(exportPath, result);
console.log('');
console.log(colorize('Profile "' + profileName + '" has been written to ' + exportPath));
profile.delete();
delete currentProfiles[profileName];
});
};
return {
startProfile: startProfile,
stopProfile: stopProfile,
};
};
|
zodern/meteor-build-profiler
| 5
|
JavaScript
|
zodern
| |||
index.js
|
JavaScript
|
module.exports = require('./.swc/node_modules/@swc/core/index.js');
|
zodern/meteor-package-install-swc
| 2
|
Npm package to allow Meteor packages to use swc
|
JavaScript
|
zodern
| ||
install.js
|
JavaScript
|
const fs = require('fs');
const path = require('path');
let folderPath = path.resolve(__dirname, './.swc');
const packageJsonPath = path.resolve(folderPath, 'package.json');
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
if (!fs.existsSync(packageJsonPath)) {
fs.writeFileSync(packageJsonPath, JSON.stringify({
name: 'swc',
version: "1.0.0",
dependencies: {
"@swc/core": "1.3.95"
}
}));
}
console.log('installing @swc/core for this platform and arch');
require('child_process').spawnSync(process.env.NODE, [
process.env.npm_execpath,
'install'
], {
cwd: folderPath,
stdio: 'inherit'
}).toString().trim();
|
zodern/meteor-package-install-swc
| 2
|
Npm package to allow Meteor packages to use swc
|
JavaScript
|
zodern
| ||
package.js
|
JavaScript
|
Package.describe({
summary: 'Build plugin to provide list of packages and their versions used by the app',
version: '0.2.2',
name: 'zodern:meteor-package-versions',
git: 'https://github.com/zodern/meteor-package-versions.git'
});
Package.registerBuildPlugin({
name: 'package-versions-compiler',
sources: [
'./plugin.js'
],
});
Package.onUse(api => {
api.use('isobuild:compiler-plugin@1.0.0')
api.versionsFrom('METEOR@1.4');
api.imply('modules');
});
|
zodern/meteor-package-versions
| 3
|
Meteor compiler to provide apps or packages with a list of packages used by the app and their versions.
|
JavaScript
|
zodern
| ||
plugin.js
|
JavaScript
|
var fs = Plugin.fs;
// Based on https://github.com/meteor/meteor/blob/d9db4f52f2ea6d706a25156768ea42e1fbb8f599/tools/utils/utils.js#L250
function parsePackageAndVersion(packageAtVersionString) {
var separatorPos = Math.max(packageAtVersionString.lastIndexOf(' '),
packageAtVersionString.lastIndexOf('@'));
if (separatorPos < 0) {
return;
}
var packageName = packageAtVersionString.slice(0, separatorPos);
var version = packageAtVersionString.slice(separatorPos + 1);
return { package: packageName, version: version };
}
// Meteor doesn't provide fs.exists, so we implement a simplified version ourselves
function exists(path) {
try {
return !!fs.statSync(path);
} catch (e) {
return false;
}
}
function PackageVersionCompiler() { }
PackageVersionCompiler.prototype.processFilesForTarget = function (files) {
var contents;
try {
contents = fs.readFileSync('./.meteor/versions', 'utf-8');
} catch (e) {
// Check if running for a package, such as `meteor test-packages`
// In that case, there will never be a .meteor/versions file
if (!exists('./package.js')) {
console.log('package.js does not exist', process.cwd());
console.error('zodern:meteor-package-versions: Unable to read .meteor/versions -', e.message);
}
files.forEach((file) => {
file.addJavaScript({
data: `module.exports = {__errorRetrievingVersions: true};`,
path: file.getPathInPackage()
});
});
return;
}
var lines = contents.split(/\r*\n\r*/);
var versions = {};
// based on https://github.com/meteor/meteor/blob/d9db4f52f2ea6d706a25156768ea42e1fbb8f599/tools/project-context.js#L1171
lines.forEach(line => {
line = line.replace(/^\s+|\s+$/g, '');
if (line === '')
return;
var packageVersion = parsePackageAndVersion(line);
if (!packageVersion)
return;
// If a package is in the file multiple times, Meteor only uses the first entry
if (packageVersion.package in versions)
return;
versions[packageVersion.package] = packageVersion.version;
});
var result = `module.exports = ${JSON.stringify(versions)}`;
files.forEach((file) => {
file.addJavaScript({
data: result,
path: file.getPathInPackage()
});
});
}
Plugin.registerCompiler({
filenames: ['.meteor-package-versions']
}, () => new PackageVersionCompiler);
|
zodern/meteor-package-versions
| 3
|
Meteor compiler to provide apps or packages with a list of packages used by the app and their versions.
|
JavaScript
|
zodern
| ||
benchmark/benchmark-concat-large.js
|
JavaScript
|
const Benchmark = require('benchmark');
const ParcelSourceMap = require('@parcel/source-map').default;
const ConcatSourceMap = require('../');
const fs = require('node:fs');
const sourcemap = require('source-map');
const largeCode = fs.readFileSync('./three.js', 'utf-8');
const largeLineCount = largeCode.split('\n').length + 1;
const largeMap = JSON.parse(fs.readFileSync('./three.js.map', 'utf-8'));
new Benchmark.Suite()
.add('@parcel/source-map', function () {
let map = new ParcelSourceMap();
map.addVLQMap(largeMap, 0);
map.addVLQMap(largeMap, largeLineCount * 1 + 1);
map.addVLQMap(largeMap, largeLineCount * 2 + 2);
map.addVLQMap(largeMap, largeLineCount * 3 + 3);
map.toVLQ();
})
.add('@zodern/source-maps', function () {
let map = new ConcatSourceMap();
map.addMap(largeMap, largeLineCount * 1 + 1);
map.addMap(largeMap, largeLineCount * 2 + 2);
map.addMap(largeMap, largeLineCount * 3 + 3);
map.build();
})
.add('@zodern/source-maps CombinedFile', function () {
let file = new ConcatSourceMap.CombinedFile();
file.addCodeWithMap('/three.js', { code: largeCode, map: largeMap });
file.addCodeWithMap('/three.js', { code: largeCode, map: largeMap });
file.addCodeWithMap('/three.js', { code: largeCode, map: largeMap });
file.build();
})
.add('source-map', {
defer: true,
fn: async (defer) => {
const sourcemapConsumer1 = await new sourcemap.SourceMapConsumer(largeMap);
const sourcemapConsumer2 = await new sourcemap.SourceMapConsumer(largeMap);
const sourcemapConsumer3 = await new sourcemap.SourceMapConsumer(largeMap);
let chunk1 = sourcemap.SourceNode.fromStringWithSourceMap(
'',
sourcemapConsumer1,
);
let chunk2 = sourcemap.SourceNode.fromStringWithSourceMap(
'',
sourcemapConsumer2,
);
let chunk3 = sourcemap.SourceNode.fromStringWithSourceMap(
'',
sourcemapConsumer3,
);
let chunk = new sourcemap.SourceNode(null, null, null, [chunk1, chunk2, chunk3]);
sourcemapConsumer1.destroy();
sourcemapConsumer2.destroy();
sourcemapConsumer3.destroy();
chunk.toStringWithSourceMap({
file: '/app.js',
});
defer.resolve();
}
})
.on('cycle', function (event) {
if (event.target.error) {
throw event.target.error;
}
console.log(String(event.target));
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ async: false })
|
zodern/source-maps
| 1
|
Concat source maps - very fast and in pure js
|
JavaScript
|
zodern
| ||
benchmark/benchmark-concat-small.js
|
JavaScript
|
const Benchmark = require('benchmark');
const ParcelSourceMap = require('@parcel/source-map').default;
const ConcatSourceMap = require('../');
const fs = require('node:fs');
const sourcemap = require('source-map');
const smallCode = fs.readFileSync('./small.js', 'utf-8');
const smallLineCount = smallCode.split('\n').length + 1;
const smallMap = JSON.parse(fs.readFileSync('./small.js.map', 'utf-8'));
new Benchmark.Suite()
.add('@parcel/source-map', function () {
let map = new ParcelSourceMap();
map.addVLQMap(smallMap, 0);
map.addVLQMap(smallMap, smallLineCount * 1 + 1);
map.addVLQMap(smallMap, smallLineCount * 2 + 2);
map.addVLQMap(smallMap, smallLineCount * 3 + 3);
map.toVLQ();
})
.add('@zodern/source-maps', function () {
let map = new ConcatSourceMap();
map.addMap(smallMap, smallLineCount * 1 + 1);
map.addMap(smallMap, smallLineCount * 2 + 2);
map.addMap(smallMap, smallLineCount * 3 + 3);
map.build();
})
.add('@zodern/source-maps CombinedFile', function () {
let file = new ConcatSourceMap.CombinedFile();
file.addCodeWithMap('/small.js', { code: smallCode, map: smallMap });
file.addCodeWithMap('/small.js', { code: smallCode, map: smallMap });
file.addCodeWithMap('/small.js', { code: smallCode, map: smallMap });
file.build();
})
.add('source-map', {
defer: true,
fn: async (defer) => {
const sourcemapConsumer1 = await new sourcemap.SourceMapConsumer(smallMap);
const sourcemapConsumer2 = await new sourcemap.SourceMapConsumer(smallMap);
const sourcemapConsumer3 = await new sourcemap.SourceMapConsumer(smallMap);
let chunk1 = sourcemap.SourceNode.fromStringWithSourceMap(
'',
sourcemapConsumer1,
);
let chunk2 = sourcemap.SourceNode.fromStringWithSourceMap(
'',
sourcemapConsumer2,
);
let chunk3 = sourcemap.SourceNode.fromStringWithSourceMap(
'',
sourcemapConsumer3,
);
let chunk = new sourcemap.SourceNode(null, null, null, [chunk1, chunk2, chunk3]);
sourcemapConsumer1.destroy();
sourcemapConsumer2.destroy();
sourcemapConsumer3.destroy();
chunk.toStringWithSourceMap({
file: '/app.js',
});
defer.resolve();
}
})
.on('cycle', function (event) {
if (event.target.error) {
throw event.target.error;
}
console.log(String(event.target));
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ async: true })
|
zodern/source-maps
| 1
|
Concat source maps - very fast and in pure js
|
JavaScript
|
zodern
| ||
benchmark/benchmark-empty.js
|
JavaScript
|
const Benchmark = require('benchmark');
const ParcelSourceMap = require('@parcel/source-map').default;
const ConcatSourceMap = require('../');
const vlq = require('vlq');
// For comparison, this is a simple implementation that doesn't have to deal
// with input source maps, and is thus 1.3 - 1.6x faster.
class EmptyMapMulti {
constructor() {
this.mappings = '';
this.sources = [];
this.sourcesContent = [];
this.lastLine = 0;
this.lastSourceLine = 0;
}
addMap(source, content, lineCount, line) {
let index = this.sources.push(source);
this.sourcesContent.push(content);
if (line < this.lastLine) {
throw new Error('Maps must be added in order from top to bottom');
}
if (this.lastLine < line) {
this.mappings += ';'.repeat(line - this.lastLine);
}
let sourceLineOffset = 0 - this.lastSourceLine;
let firstMapping = sourceLineOffset === 0 ?
'AAAA;' :
`AC${vlq.encode(sourceLineOffset)}A;`;
if (lineCount > 0) {
this.mappings += firstMapping;
}
if (lineCount > 1) {
this.mappings += 'AACA;'.repeat(lineCount - 1);
}
this.lastSourceLine = lineCount > 0 ? lineCount - 1 : 0;
this.lastLine = line + lineCount;
}
build() {
return {
mappings: this.mappings,
sources: this.sources,
sourcesContent: this.sourcesContent,
names: [],
version: 3
}
}
}
let smallLineCount = 10;
let inputSmall = '\n'.repeat(smallLineCount);
let medLineCount = 10000;
let inputMedium = '\n'.repeat(medLineCount);
let largeLineCount = 1000000;
let inputLarge = '\n'.repeat(largeLineCount);
new Benchmark.Suite()
.add('@parcel/source-map - small', function (){
let map = new ParcelSourceMap();
map.addEmptyMap('test1', inputSmall, 0);
map.addEmptyMap('test2', inputSmall, smallLineCount * 1 + 1);
map.addEmptyMap('test3', inputSmall, smallLineCount * 2 + 2);
map.toVLQ();
})
.add('@parcel/source-map - medium', function (){
let map = new ParcelSourceMap();
map.addEmptyMap('test1', inputMedium, 0);
map.addEmptyMap('test2', inputMedium, medLineCount * 1 + 1);
map.addEmptyMap('test3', inputMedium, medLineCount * 2 + 2);
map.toVLQ();
})
.add('@parcel/source-map - large', function (){
let map = new ParcelSourceMap();
map.addEmptyMap('test1', inputLarge, 0);
map.addEmptyMap('test2', inputLarge, largeLineCount * 1 + 1);
map.addEmptyMap('test3', inputLarge, largeLineCount * 2 + 2);
map.toVLQ();
})
.add('@zodern/source-maps - small', function () {
let map = new ConcatSourceMap();
map.addEmptyMap('test1', inputSmall, 0);
map.addEmptyMap('test2', inputSmall, smallLineCount * 1 + 1);
map.addEmptyMap('test3', inputSmall, smallLineCount * 2 + 2);
map.build();
})
.add('@zodern/source-maps - medium', function () {
let map = new ConcatSourceMap();
map.addEmptyMap('test1', inputMedium, 0);
map.addEmptyMap('test2', inputMedium, medLineCount * 1 + 1);
map.addEmptyMap('test3', inputMedium, medLineCount * 2 + 2);
map.build();
})
.add('@zodern/source-maps - large', function () {
let map = new ConcatSourceMap();
map.addEmptyMap('test1', inputLarge, 0);
map.addEmptyMap('test2', inputLarge, largeLineCount * 1 + 1);
map.addEmptyMap('test3', inputLarge, largeLineCount * 2 + 2);
map.build();
})
.add('@zodern/source-maps - small with lineCount', function () {
let map = new ConcatSourceMap();
map.addEmptyMap('test1', inputSmall, 0, smallLineCount);
map.addEmptyMap('test2', inputSmall, smallLineCount * 1 + 1, smallLineCount);
map.addEmptyMap('test3', inputSmall, smallLineCount * 2 + 2, smallLineCount);
map.build();
})
.add('@zodern/source-maps - medium with lineCount', function () {
let map = new ConcatSourceMap();
map.addEmptyMap('test1', inputMedium, 0, medLineCount);
map.addEmptyMap('test2', inputMedium, medLineCount * 1 + 1, medLineCount);
map.addEmptyMap('test3', inputMedium, medLineCount * 2 + 2, medLineCount);
map.build();
})
.add('@zodern/source-maps - large with lineCount', function () {
let map = new ConcatSourceMap();
map.addEmptyMap('test1', inputLarge, 0, largeLineCount);
map.addEmptyMap('test2', inputLarge, largeLineCount * 1 + 1, largeLineCount);
map.addEmptyMap('test3', inputLarge, largeLineCount * 2 + 2, largeLineCount);
map.build();
})
// .add('custom - small', function () {
// let map = new EmptyMapMulti();
// map.addMap('test1', inputSmall,smallLineCount, 0);
// map.addMap('test2', inputSmall,smallLineCount, smallLineCount * 1 + 1);
// map.addMap('test3', inputSmall,smallLineCount, smallLineCount * 2 + 2);
// map.build();
// })
// .add('custom - medium', function () {
// let map = new EmptyMapMulti();
// map.addMap('test1', inputMedium, medLineCount, 0);
// map.addMap('test2', inputMedium, medLineCount, medLineCount * 1 + 1);
// map.addMap('test3', inputMedium, medLineCount, medLineCount * 2 + 2);
// map.build();
// })
// .add('custom - large', function () {
// let map = new EmptyMapMulti();
// map.addMap('test1', inputLarge, largeLineCount, 0);
// map.addMap('test2', inputLarge, largeLineCount, largeLineCount * 1 + 1);
// map.addMap('test3', inputLarge, largeLineCount, largeLineCount * 2 + 2);
// map.build();
// })
.on('cycle', function (event) {
if (event.target.error) {
throw event.target.error;
}
console.log(String(event.target));
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ async: true })
|
zodern/source-maps
| 1
|
Concat source maps - very fast and in pure js
|
JavaScript
|
zodern
| ||
benchmark/small.js
|
JavaScript
|
////////////////////////////////////////////////////////////////////////////////
// //
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// Source maps are supported by all recent versions of Chrome, Safari, //
// and Firefox, and by Internet Explorer 11. //
// //
////////////////////////////////////////////////////////////////////////////////
Package["core-runtime"].queue("reload", ["meteor", "ecmascript", "modules", "ecmascript-runtime", "babel-runtime", "promise", "dynamic-import", "ecmascript-runtime-client"], function () {/* Imports */
var Meteor = Package.meteor.Meteor;
var global = Package.meteor.global;
var meteorEnv = Package.meteor.meteorEnv;
var meteorInstall = Package.modules.meteorInstall;
var Promise = Package.promise.Promise;
/* Package-scope variables */
var Reload;
var require = meteorInstall({"node_modules":{"meteor":{"reload":{"reload.js":function module(require,exports,module){
////////////////////////////////////////////////////////////////////////////////
// //
// packages/reload/reload.js //
// //
////////////////////////////////////////////////////////////////////////////////
module.export({
Reload: () => Reload
});
const Reload = {};
const reloadSettings = Meteor.settings && Meteor.settings.public && Meteor.settings.public.packages && Meteor.settings.public.packages.reload || {};
function debug(message, context) {
if (!reloadSettings.debug) {
return;
}
// eslint-disable-next-line no-console
console.log("[reload] ".concat(message), JSON.stringify(context));
}
const KEY_NAME = 'Meteor_Reload';
let old_data = {};
// read in old data at startup.
let old_json;
// This logic for sessionStorage detection is based on browserstate/history.js
let safeSessionStorage = null;
try {
// This throws a SecurityError on Chrome if cookies & localStorage are
// explicitly disabled
//
// On Firefox with dom.storage.enabled set to false, sessionStorage is null
//
// We can't even do (typeof sessionStorage) on Chrome, it throws. So we rely
// on the throw if sessionStorage == null; the alternative is browser
// detection, but this seems better.
safeSessionStorage = window.sessionStorage;
// Check we can actually use it
if (safeSessionStorage) {
safeSessionStorage.setItem('__dummy__', '1');
safeSessionStorage.removeItem('__dummy__');
} else {
// Be consistently null, for safety
safeSessionStorage = null;
}
} catch (e) {
// Expected on chrome with strict security, or if sessionStorage not supported
safeSessionStorage = null;
}
// Exported for test.
Reload._getData = function () {
return safeSessionStorage && safeSessionStorage.getItem(KEY_NAME);
};
if (safeSessionStorage) {
old_json = Reload._getData();
safeSessionStorage.removeItem(KEY_NAME);
} else {
// Unsupported browser (IE 6,7) or locked down security settings.
// No session resumption.
// Meteor._debug("XXX UNSUPPORTED BROWSER/SETTINGS");
}
if (!old_json) old_json = '{}';
let old_parsed = {};
try {
old_parsed = JSON.parse(old_json);
if (typeof old_parsed !== 'object') {
Meteor._debug('Got bad data on reload. Ignoring.');
old_parsed = {};
}
} catch (err) {
Meteor._debug('Got invalid JSON on reload. Ignoring.');
}
if (old_parsed.reload && typeof old_parsed.data === 'object') {
// Meteor._debug("Restoring reload data.");
old_data = old_parsed.data;
}
let providers = [];
////////// External API //////////
// Packages that support migration should register themselves by calling
// this function. When it's time to migrate, callback will be called
// with one argument, the "retry function," and an optional 'option'
// argument (containing a key 'immediateMigration'). If the package
// is ready to migrate, it should return [true, data], where data is
// its migration data, an arbitrary JSON value (or [true] if it has
// no migration data this time). If the package needs more time
// before it is ready to migrate, it should return false. Then, once
// it is ready to migrating again, it should call the retry
// function. The retry function will return immediately, but will
// schedule the migration to be retried, meaning that every package
// will be polled once again for its migration data. If they are all
// ready this time, then the migration will happen. name must be set if there
// is migration data. If 'immediateMigration' is set in the options
// argument, then it doesn't matter whether the package is ready to
// migrate or not; the reload will happen immediately without waiting
// (used for OAuth redirect login).
//
Reload._onMigrate = function (name, callback) {
debug('_onMigrate', {
name
});
if (!callback) {
// name not provided, so first arg is callback.
callback = name;
name = undefined;
debug('_onMigrate no callback');
}
providers.push({
name: name,
callback: callback
});
};
// Called by packages when they start up.
// Returns the object that was saved, or undefined if none saved.
//
Reload._migrationData = function (name) {
debug('_migrationData', {
name
});
return old_data[name];
};
// Options are the same as for `Reload._migrate`.
const pollProviders = function (tryReload, options) {
debug('pollProviders', {
options
});
tryReload = tryReload || function () {};
options = options || {};
const {
immediateMigration
} = options;
debug("pollProviders is ".concat(immediateMigration ? '' : 'NOT ', "immediateMigration"), {
options
});
const migrationData = {};
let allReady = true;
providers.forEach(p => {
const {
callback,
name
} = p || {};
const [ready, data] = callback(tryReload, options) || [];
debug("pollProviders provider ".concat(name || 'unknown', " is ").concat(ready ? 'ready' : 'NOT ready'), {
options
});
if (!ready) {
allReady = false;
}
if (data !== undefined && name) {
migrationData[name] = data;
}
});
if (allReady) {
debug('pollProviders allReady', {
options,
migrationData
});
return migrationData;
}
if (immediateMigration) {
debug('pollProviders immediateMigration', {
options,
migrationData
});
return migrationData;
}
return null;
};
// Options are:
// - immediateMigration: true if the page will be reloaded immediately
// regardless of whether packages report that they are ready or not.
Reload._migrate = function (tryReload, options) {
debug('_migrate', {
options
});
// Make sure each package is ready to go, and collect their
// migration data
const migrationData = pollProviders(tryReload, options);
if (migrationData === null) {
return false; // not ready yet..
}
let json;
try {
// Persist the migration data
json = JSON.stringify({
data: migrationData,
reload: true
});
} catch (err) {
Meteor._debug("Couldn't serialize data for migration", migrationData);
throw err;
}
if (safeSessionStorage) {
try {
safeSessionStorage.setItem(KEY_NAME, json);
} catch (err) {
// We should have already checked this, but just log - don't throw
Meteor._debug("Couldn't save data for migration to sessionStorage", err);
}
} else {
Meteor._debug('Browser does not support sessionStorage. Not saving migration state.');
}
return true;
};
// Allows tests to isolate the list of providers.
Reload._withFreshProvidersForTest = function (f) {
const originalProviders = providers.slice(0);
providers = [];
try {
f();
} finally {
providers = originalProviders;
}
};
// Migrating reload: reload this page (presumably to pick up a new
// version of the code or assets), but save the program state and
// migrate it over. This function returns immediately. The reload
// will happen at some point in the future once all of the packages
// are ready to migrate.
//
let reloading = false;
Reload._reload = function (options) {
debug('_reload', {
options
});
options = options || {};
if (reloading) {
debug('reloading in progress already', {
options
});
return;
}
reloading = true;
function tryReload() {
debug('tryReload');
setTimeout(reload, 1);
}
function forceBrowserReload() {
debug('forceBrowserReload');
// We'd like to make the browser reload the page using location.replace()
// instead of location.reload(), because this avoids validating assets
// with the server if we still have a valid cached copy. This doesn't work
// when the location contains a hash however, because that wouldn't reload
// the page and just scroll to the hash location instead.
if (window.location.hash || window.location.href.endsWith('#')) {
window.location.reload();
return;
}
window.location.replace(window.location.href);
}
function reload() {
debug('reload');
if (!Reload._migrate(tryReload, options)) {
return;
}
if (Meteor.isCordova) {
WebAppLocalServer.switchToPendingVersion(() => {
forceBrowserReload();
});
return;
}
forceBrowserReload();
}
tryReload();
};
////////////////////////////////////////////////////////////////////////////////
}}}}},{
"extensions": [
".js",
".json"
]
});
/* Exports */
return {
export: function () { return {
Reload: Reload
};},
require: require,
eagerModulePaths: [
"/node_modules/meteor/reload/reload.js"
],
mainModulePath: "/node_modules/meteor/reload/reload.js"
}});
|
zodern/source-maps
| 1
|
Concat source maps - very fast and in pure js
|
JavaScript
|
zodern
| ||
index.js
|
JavaScript
|
const vlq = require('vlq');
class SourceMap {
constructor() {
this.mappings = '';
this.sources = [];
this.sourcesContent = [];
this.names = [];
this.lastLine = 0;
this.lastSourceLine = 0;
this.lastName = 0;
this.lastSource = 0;
this.lastSourceCol = 0;
this._endsOnNewLine = true;
}
addEmptyMap(source, content, line, lineCount) {
this._endOnNewLine();
if (line < this.lastLine) {
throw new Error('Maps must be added in order from top to bottom');
}
if (this.lastLine < line) {
this.mappings += ';'.repeat(line - this.lastLine);
}
lineCount = lineCount || (countNewLines(content) + 1);
let firstMapping = vlq.encode([
0,
this.sources.length - this.lastSource,
0 - this.lastSourceLine,
-this.lastSourceCol
]) + ';';
if (lineCount > 0) {
this.mappings += firstMapping;
}
if (lineCount > 1) {
this.mappings += 'AACA;'.repeat(lineCount - 1);
}
this.sources.push(source);
this.sourcesContent.push(content);
this.lastSource = this.sources.length - 1
this.lastSourceLine = lineCount - 1;
this.lastSourceCol = 0
this.lastLine = line + lineCount;
this._endsOnNewLine = true;
}
addMap({ mappings, sources, sourcesContent, names = [] }, line = 0) {
if (mappings.length === 0) {
return;
}
this._endOnNewLine();
let {
lastSource,
lastSourceLine,
lastSourceCol,
lastName,
modifications,
lines
} = analyzeMappings(mappings, names && names.length > 0);
if (this.lastLine < line) {
this.mappings += ';'.repeat(line - this.lastLine);
}
let modifiedMappings = '';
let prevIndex = 0;
modifications.forEach(update => {
modifiedMappings += mappings.substring(prevIndex, update.i);
if (update.onlyUpdateName) {
let namesAdjustment = this.names.length - this.lastName;
modifiedMappings += vlq.encode([
update.values[0],
update.values[1],
update.values[2],
update.values[3],
namesAdjustment + update.values[4]
]);
lastName += namesAdjustment;
} else {
let [generatedCol, source, sourceLine, sourceCol] = update.values;
let sourceAdjustment = this.sources.length - this.lastSource;
let sourceLineAdjustment = 0 - this.lastSourceLine;
let sourceColAdjustment = -this.lastSourceCol;
modifiedMappings += vlq.encode([
generatedCol,
sourceAdjustment + source,
sourceLineAdjustment + sourceLine,
sourceColAdjustment + sourceCol
]);
lastSource += sourceAdjustment;
lastSourceLine += sourceLineAdjustment;
lastSourceCol += sourceColAdjustment;
if (update.size === 5) {
let namesAdjustment = this.names.length - this.lastName;
modifiedMappings += vlq.encode(namesAdjustment + update.values[4]);
lastName += namesAdjustment;
}
}
prevIndex = update.end;
});
modifiedMappings += mappings.substring(prevIndex);
// Caching this here is significantly faster than doing it in _endOnNewLine
this._endsOnNewLine = modifiedMappings.charAt(modifiedMappings.length - 1) === ';';
if (this._endsOnNewLine) {
lines += 1;
}
if (sourcesContent) {
while(this.sourcesContent.length < this.sources.length) {
this.sourcesContent.push(null);
}
this.sourcesContent.push(...sourcesContent);
}
this.sources.push(...sources);
this.names.push(...names);
this.lastSource += lastSource;
this.lastSourceLine += lastSourceLine;
this.lastSourceCol += lastSourceCol;
this.lastName += lastName;
this.lastLine = lines + (line - 1);
this.mappings += modifiedMappings;
}
_endOnNewLine() {
if (!this._endsOnNewLine) {
this.mappings += ';';
this.lastLine += 1;
}
}
build() {
return {
mappings: this.mappings,
sources: this.sources,
sourcesContent: this.sourcesContent,
names: this.names,
version: 3
}
}
}
module.exports = SourceMap;
function analyzeMappings(mappings, hasNames) {
// If there are no names, then no need to update them
let updatedNames = !hasNames;
let updatedFirstMapping = false;
let modifications = [];
let lines = 0;
let pos = new Int32Array(5);
let col = 0;
let end;
let i;
let char;
let j;
for (i = 0; i < mappings.length; i++) {
let lineEnd = mappings.indexOf(';', i);
if (lineEnd === -1) {
lineEnd = mappings.length;
}
col = 0;
lines += 1;
for (j = i; j < lineEnd; j++) {
end = j + 1;
inner: for (; end < lineEnd; end++) {
char = mappings.charAt(end);
if (char === ',') {
break inner;
}
}
let size = decode(mappings, pos, j, end);
if (!updatedFirstMapping && size > 1) {
updatedFirstMapping = true;
let decoded = new Int32Array(5);
decode(mappings, decoded, j, end)
if (size === 5) {
// Adjust names
updatedNames = true;
}
modifications.push({ i: j, end, values: decoded, size, onlyUpdateName: false });
} else if (!updatedNames && size === 5) {
let decoded = new Int32Array(5);
decode(mappings, decoded, j, end)
modifications.push({ i: j, end, values: decoded, size, onlyUpdateName: true });
updatedNames = true;
}
j = end;
}
i = lineEnd;
}
return {
lastSource: pos[1],
lastSourceLine: pos[2],
lastSourceCol: pos[3],
lastName: pos[4],
lines: Math.max(1, lines),
modifications
};
}
module.exports.analyzeMappings = analyzeMappings;
function countNewLines(code) {
let lastIndex = code.indexOf('\n');
let count = 0;
while (lastIndex > -1) {
count += 1;
lastIndex = code.indexOf('\n', lastIndex + 1);
}
return count;
}
let charIntegers = new Int8Array(300);
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
.split('')
.forEach(function (char, i) {
charIntegers[char.charCodeAt(0)] = i;
});
function decode(string, pos, index, end) {
let shift = 0;
let value = 0;
let posIndex = 0;
for (let i = index; i < end; i += 1) {
let integer = charIntegers[string.charCodeAt(i)];
const has_continuation_bit = integer & 32;
integer &= 31;
value += integer << shift;
if (has_continuation_bit) {
shift += 5;
} else {
const should_negate = value & 1;
value >>>= 1;
if (should_negate) {
pos[posIndex++] += value === 0 ? -0x80000000 : -value;
} else {
if (posIndex == 1) {
}
pos[posIndex++] += value;
}
// reset
value = shift = 0;
}
}
return posIndex;
}
class CombinedFile {
constructor() {
this._chunks = [];
this._lineOffset = 0;
this._addedFiles = 0;
}
addGeneratedCode(code) {
let lineCount = countNewLines(code);
this._chunks.push(code);
this._lineOffset += lineCount;
}
addCodeWithMap(sourceName, {
code,
map,
header,
footer
}) {
this._addedFiles += 1;
let newLines = countNewLines(code);
if (header) {
this.addGeneratedCode(header);
}
this._chunks.push({
code,
map,
sourceName,
lineOffset: this._lineOffset,
lines: newLines + 1
});
if (footer) {
this.addGeneratedCode(footer);
}
this._lineOffset += newLines;
}
_buildWithMap() {
let code = '';
let sourceMap = new SourceMap();
this._chunks.forEach(chunk => {
if (typeof chunk === 'string') {
code += chunk;
} else if (typeof chunk === 'object') {
code += chunk.code;
if (chunk.map) {
sourceMap.addMap(chunk.map, chunk.lineOffset)
} else {
sourceMap.addEmptyMap(chunk.sourceName, chunk.code, chunk.lineOffset, chunk.lines);
}
} else {
throw new Error(`unrecognized chunk type, ${typeof chunk}`);
}
});
let map = sourceMap.build();
return { code, map };
}
// Optimization for when there are 1 or 0 files.
// We can avoid parsing the source map if there is one, and instead
// modify it to account for the offset from any generated code.
_buildWithBiasedMap() {
let file;
let header = '';
let footer = '';
this._chunks.forEach(chunk => {
if (typeof chunk === 'string') {
if (file) {
footer += chunk;
} else {
header += chunk;
}
} else if (typeof chunk === 'object') {
if (file) {
throw new Error('_buildWithBiasedMap does not support multiple files');
}
file = chunk;
} else {
throw new Error(`unrecognized chunk type, ${typeof chunk}`);
}
});
if (!file) {
return { code: header + footer, map: null };
}
let map = file.map;
if (!map) {
let sourceMap = new SourceMap();
sourceMap.addEmptyMap(file.sourceName, file.code, file.lineOffset, file.lines);
map = sourceMap.build();
} else {
// Bias the input sourcemap to account for the lines added by the header
// This is much faster than parsing and re-encoding the sourcemap
let headerMappings = ';'.repeat(file.lineOffset);
map = Object.assign({}, map);
map.mappings = headerMappings + map.mappings;
}
return {
code: header + file.code + footer,
map
};
}
build() {
let code;
let map;
if (this._addedFiles < 2) {
({ code, map } = this._buildWithBiasedMap());
} else {
({ code, map } = this._buildWithMap());
}
return {
code,
map
};
}
}
module.exports.CombinedFile = CombinedFile;
|
zodern/source-maps
| 1
|
Concat source maps - very fast and in pure js
|
JavaScript
|
zodern
| ||
test/test.js
|
JavaScript
|
const SourceMap = require('../index.js');
const assert = require('assert');
describe('single input map', () => {
it('should leave mappings as is', () => {
let inputMappings = 'AAAA;ACAA;';
let input = { mappings: inputMappings, sources: ['a'], sourcesContent: ['a'] };
let sm = new SourceMap();
sm.addMap(input);
const map = sm.build();
assert.deepStrictEqual(map, {
mappings: inputMappings,
names: [],
sources: ['a'],
sourcesContent: ['a'],
version: 3
});
});
it('should offset by line', () => {
let input = 'AAAA;ACAA;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'] }, 3);
const { mappings } = sm.build();
assert.equal(';;;AAAA;ACAA;', mappings);
});
it('should handle multiple mappings on one line', () => {
let input = 'AAAA,CCAA;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'] }, 3);
const { mappings } = sm.build();
assert.equal(';;;AAAA,CCAA;', mappings);
});
it('should handle empty lines in middle of mappings', () => {
let input = 'AAAA;;;;;CCAA';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'] }, 0);
const { mappings } = sm.build();
assert.equal('AAAA;;;;;CCAA', mappings);
});
it('should handle first mappings with only a generated col', () => {
let input = 'C,C,C,C,CAAA;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'] }, 0);
const { mappings } = sm.build();
assert.equal('C,C,C,C,CAAA;', mappings);
});
it('should handle modifying separate names mapping', () => {
let input = 'C,C,C,C,CAAA,AAAAC;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['a'] }, 0);
const { mappings } = sm.build();
assert.equal('C,C,C,C,CAAA,AAAAC;', mappings);
});
});
describe('two input maps', () => {
it('should concatenate', () => {
let input = 'AAAA;AACA;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'] });
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'] }, 5);
const map = sm.build();
assert.deepStrictEqual(map, {
mappings: 'AAAA;AACA;;;;ACDA;AACA;',
sources: ['a', 'a'],
sourcesContent: ['a', 'a'],
names: [],
version: 3
});
});
it('should handle names', () => {
let input = 'AAAAA;AACA;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['b'] });
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['b'] }, 5);
const { mappings } = sm.build();
assert.equal('AAAAA;AACA;;;;ACDAC;AACA;', mappings);
});
it('should handle multiple names', () => {
let input = 'AAAAA,MAAM,CAACC,MAAM;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['a', 'b'] });
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['c', 'd'] }, 5);
const map = sm.build();
assert.deepStrictEqual(map, {
mappings: 'AAAAA,MAAM,CAACC,MAAM;;;;;ACAbC,MAAM,CAACC,MAAM;',
sources: ['a', 'a'],
sourcesContent: ['a', 'a'],
names: ['a', 'b', 'c', 'd'],
version: 3
});
});
it('should handle maps without sourcesContent', () => {
let inputMappings = 'AAAA;ACAA;';
let input = { mappings: inputMappings, sources: ['a'] };
let sm = new SourceMap();
sm.addMap(input);
sm.addMap({ mappings: inputMappings, sources: ['b'], sourcesContent: ['// b'] }, 3);
sm.addMap(input);
const map = sm.build();
assert.deepStrictEqual(map, {
mappings: 'AAAA;ACAA;;AAAA;ACAA;AAAA;ACAA;',
names: [],
sources: ['a', 'b', 'a'],
sourcesContent: [null, '// b'],
version: 3
});
});
});
describe('three input maps', () => {
it('should account for adjustments made to second map', () => {
let input = 'AAAAA,MAAM,CAACC,MAAM;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['a', 'b'] });
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['c', 'd'] }, 5);
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['c', 'd'] }, 6);
const map = sm.build();
assert.deepStrictEqual(map, {
mappings: 'AAAAA,MAAM,CAACC,MAAM;;;;;ACAbC,MAAM,CAACC,MAAM;ACAbC,MAAM,CAACC,MAAM;',
sources: ['a', 'a', 'a'],
sourcesContent: ['a', 'a', 'a'],
names: ['a', 'b', 'c', 'd', 'c', 'd'],
version: 3
});
});
it('should account for adjustments made to separate name', () => {
let input = 'AAAA,MAAMA,CAACC,MAAM;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['a', 'b'] });
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['c', 'd'] }, 5);
sm.addMap({ mappings: input, sources: ['a'], sourcesContent: ['a'], names: ['c', 'd'] }, 6);
const { mappings } = sm.build();
assert.equal('AAAA,MAAMA,CAACC,MAAM;;;;;ACAb,MAAMC,CAACC,MAAM;ACAb,MAAMC,CAACC,MAAM;', mappings);
});
});
describe('emptyMap', () => {
it('should generate empty map', () => {
let sm = new SourceMap();
sm.addEmptyMap('test.js', '\n\n\n\n', 5);
const map = sm.build();
assert.deepStrictEqual(map, {
mappings: ';;;;;AAAA;AACA;AACA;AACA;AACA;',
sources: ['test.js'],
sourcesContent: ['\n\n\n\n'],
names: [],
version: 3
});
});
it('should reset with first mapping', () => {
let input = 'AAAA,MAMAA,CAACC,MAAM;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a', 'b'], sourcesContent: ['a', 'b'], names: ['a', 'b'] });
sm.addEmptyMap('test.js', '\n\n', 2);
const { mappings } = sm.build();
assert.equal(mappings, 'AAAA,MAMAA,CAACC,MAAM;;AENP;AACA;AACA;')
});
it('should update last values', () => {
let input = 'AAAA,MAMAA,CAACC,MAAM;';
let sm = new SourceMap();
sm.addMap({ mappings: input, sources: ['a', 'b'], sourcesContent: ['a', 'b'], names: ['a', 'b'] });
sm.addEmptyMap('test.js', '1\n2\n3', 2);
sm.addEmptyMap('test.js', '1\n2\n3', 6);
const { mappings } = sm.build();
assert.equal(mappings, 'AAAA,MAMAA,CAACC,MAAM;;AENP;AACA;AACA;;ACFA;AACA;AACA;')
});
});
describe('CombinedFile', () => {
it('should support only generated code', () => {
let file = new SourceMap.CombinedFile();
file.addGeneratedCode('test\ntest2\nhello');
let out = file.build();
assert.deepStrictEqual(out, { code: 'test\ntest2\nhello', map: null });
});
it('should support single file with map', () => {
let file = new SourceMap.CombinedFile();
file.addGeneratedCode('test');
file.addGeneratedCode('\n');
file.addCodeWithMap('/test.js', {
code: 'var i = 0;\ni++\n;',
map: {
mappings: 'AAAA;AACA;ACFA;',
sources: ['/input.js']
},
header: '// test.js\n\n',
footer: '// end\n'
});
let out = file.build();
assert.deepStrictEqual(out, {
code: 'test\n// test.js\n\nvar i = 0;\ni++\n;// end\n',
map: {
mappings: ';;;AAAA;AACA;ACFA;',
sources: ['/input.js']
}
});
});
it('should support single file without map', () => {
let file = new SourceMap.CombinedFile();
file.addGeneratedCode('test');
file.addGeneratedCode('\n');
file.addCodeWithMap('/test.js', {
code: 'var i = 0;\ni++\n;',
header: '// test.js\n\n',
footer: '// end\n'
});
let out = file.build();
assert.deepStrictEqual(out, {
code: 'test\n// test.js\n\nvar i = 0;\ni++\n;// end\n',
map: {
names: [],
mappings: ';;;AAAA;AACA;AACA;',
sources: ['/test.js'],
sourcesContent: ['var i = 0;\ni++\n;'],
version: 3
}
});
});
it('should support multiple files, one without a map', () => {
let file = new SourceMap.CombinedFile();
file.addGeneratedCode('test');
file.addGeneratedCode('\n');
file.addCodeWithMap('/test.js', {
code: 'var i = 0;\ni++\n;',
header: '// test.js\n\n',
footer: '// end\n'
});
file.addCodeWithMap('/test2.js', { code: 'alert("message");' })
let out = file.build();
assert.deepStrictEqual(out, {
code: 'test\n// test.js\n\nvar i = 0;\ni++\n;// end\nalert("message");',
map: {
names: [],
mappings: ';;;AAAA;AACA;AACA;ACFA;',
sources: ['/test.js', '/test2.js'],
sourcesContent: ['var i = 0;\ni++\n;', 'alert("message");'],
version: 3
}
});
});
it('should handle empty mappings', () => {
const file = new SourceMap.CombinedFile();
file.addCodeWithMap('/1.js', { code: 'very long text 1', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "" } });
file.addGeneratedCode('\n\n');
file.addCodeWithMap('/2.js', { code: 'very long text 2', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "AAAA" } });
let out = file.build();
assert.deepStrictEqual(out, {
code: 'very long text 1\n\nvery long text 2',
map: {
names: [],
mappings: ';;AAAA',
sources: ['<anon>'],
sourcesContent: [],
version: 3
}
})
});
it('should put mappings on right lines', () => {
const file = new SourceMap.CombinedFile();
file.addCodeWithMap('/1.js', { code: 'very long text 1', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "AAAA" } });
file.addGeneratedCode('\n\n');
file.addCodeWithMap('/2.js', { code: 'very long text 2', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "AAAA" } });
file.addGeneratedCode('\n\n');
file.addCodeWithMap('/3.js', { code: 'very long text 3', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "AAAA" } });
file.addGeneratedCode('\n\n');
file.addCodeWithMap('/4.js', { code: 'very long text 4', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "AAAA" } });
file.addGeneratedCode('\n\n');
file.addCodeWithMap('/5.js', { code: 'very long text 5', map: { "version": 3, "sources": ["<anon>"], "names": [], "mappings": "AAAA" } });
let out = file.build();
assert.deepStrictEqual(out, {
code: 'very long text 1\n\nvery long text 2\n\nvery long text 3\n\nvery long text 4\n\nvery long text 5',
map: {
names: [],
mappings: 'AAAA;;ACAA;;ACAA;;ACAA;;ACAA',
sources: ['<anon>', '<anon>', '<anon>', '<anon>', '<anon>'],
sourcesContent: [],
version: 3
}
})
});
});
|
zodern/source-maps
| 1
|
Concat source maps - very fast and in pure js
|
JavaScript
|
zodern
| ||
.dumirc.ts
|
TypeScript
|
import { defineConfig } from 'dumi';
import path from 'path';
const name = 'antd-geek-theme-sample';
const isProdSite =
process.env.PREVIEW !== 'true' && process.env.NODE_ENV === 'production';
export default defineConfig({
alias: {
[`${name}$`]: path.resolve('src'),
[`${name}/es`]: path.resolve('src'),
},
mfsu: false,
favicons: ['https://avatars0.githubusercontent.com/u/9441414?s=200&v=4'],
themeConfig: {
name: 'Geek Theme',
logo: 'https://avatars0.githubusercontent.com/u/9441414?s=200&v=4',
},
styles: [
`
html .dumi-default-hero-title {
font-size: 120px;
}
.dumi-default-previewer-demo {
position: relative;
min-height: 300px;
}
`,
],
base: isProdSite ? `/${name}/` : '/',
publicPath: isProdSite ? `/${name}/` : '/',
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.eslintrc.js
|
JavaScript
|
module.exports = {
extends: [require.resolve('@umijs/fabric/dist/eslint')],
rules: {
'default-case': 0,
'import/no-extraneous-dependencies': 0,
'react-hooks/exhaustive-deps': 0,
'react/no-find-dom-node': 0,
'react/no-did-update-set-state': 0,
'react/no-unused-state': 1,
'react/sort-comp': 0,
'jsx-a11y/label-has-for': 0,
'jsx-a11y/label-has-associated-control': 0,
},
};
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.fatherrc.js
|
JavaScript
|
import { defineConfig } from 'father';
export default defineConfig({
plugins: ['@rc-component/father-plugin'],
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
docs/examples/theme.tsx
|
TypeScript (TSX)
|
/* eslint no-console:0 */
import {
Button,
Checkbox,
ConfigProvider,
Divider,
Radio,
Space,
Switch,
// Tag,
Typography,
theme,
Spin,
Card,
} from 'antd';
import React from 'react';
import { ThemeProvider, Text } from '../../src';
// const { CheckableTag } = Tag;
const Holder = (props: { children?: React.ReactNode }) => {
const { token } = theme.useToken();
const { colorBgContainer, padding } = token;
return (
<div style={{ background: colorBgContainer, paddingInline: padding }}>
{props.children}
</div>
);
};
const Demo = () => {
const [disabled, setDisabled] = React.useState<boolean>(false);
const [componentDisabled, setComponentDisabled] =
React.useState<boolean>(false);
// const [checkedTags, setCheckedTags] = React.useState<number[]>([0, 2]);
return (
<>
<ConfigProvider
theme={{
algorithm: theme.darkAlgorithm,
}}
>
<ThemeProvider disabled={disabled}>
<Holder>
<Typography.Title>
Hello, <Text>Geek Theme</Text>
</Typography.Title>
<Typography.Paragraph>
This theme is base on the token system of Ant Design.{' '}
<Text>Have a nice day~</Text>
</Typography.Paragraph>
<Space>
<Switch
checkedChildren="Enabled"
unCheckedChildren="Disable"
checked={!disabled}
onChange={() => setDisabled((d) => !d)}
/>
<Switch
checkedChildren="Component Disabled"
unCheckedChildren="Component Disabled"
checked={componentDisabled}
onChange={() => setComponentDisabled((d) => !d)}
/>
</Space>
<Divider />
<ConfigProvider componentDisabled={componentDisabled}>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
paddingBlock: 32,
rowGap: 32,
}}
>
<Checkbox.Group
options={new Array(3)
.fill(null)
.map((_, index) => `option-${index}`)}
/>
<Radio.Group
defaultValue="default"
options={['default', 'apple', 'orange']}
/>
<Space>
<Button type="primary">Primary</Button>
<Button>Default</Button>
<Button type="dashed">Dashed</Button>
<Button type="primary" danger>
Danger
</Button>
<Button type="text">Text</Button>
<Button type="link">Link</Button>
</Space>
{/* CheckedTag has bug that not support CP className yet */}
{/* <Space>
<Switch
checkedChildren="So Geek"
unCheckedChildren="So Geek"
defaultChecked
/>
<Tag onClick={() => {}}>Tag</Tag>
{new Array(3).fill(null).map((_, index) => (
<CheckableTag
key={index}
checked={checkedTags.includes(index)}
onChange={(checked) => {
setCheckedTags((tags) => {
if (checked) {
return [...tags, index];
}
return tags.filter((t) => t !== index);
});
}}
>
Tag {index}
</CheckableTag>
))}
</Space> */}
<Space>
<Spin size="small" />
<Spin />
<Spin size="large" />
</Space>
<Card title="Card Title" size="small" style={{ minWidth: 300 }}>
Hello, <Text>Geek Theme</Text>
</Card>
</div>
</ConfigProvider>
</Holder>
</ThemeProvider>
</ConfigProvider>
</>
);
};
export default Demo;
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
jest.config.js
|
JavaScript
|
module.exports = {
setupFiles: ['./tests/setup.js'],
};
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/Text/index.tsx
|
TypeScript (TSX)
|
import * as React from 'react';
import { ConfigProvider, Typography } from 'antd';
import classNames from 'classnames';
import useStyle from './style';
export type TextProps = React.HtmlHTMLAttributes<HTMLSpanElement>;
export default function Text(props: TextProps) {
const { children, className, ...restProps } = props;
const { getPrefixCls } = React.useContext(ConfigProvider.ConfigContext);
const prefixCls = getPrefixCls('geek-text');
useStyle(prefixCls);
return (
<Typography.Text {...restProps} className={classNames(prefixCls)}>
{children}
</Typography.Text>
);
}
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/Text/style.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from '../styles/styleUtil';
import { background } from '../styles/gradientUtil';
import { DOT_PREFIX } from '../constant';
// ============================== Border ==============================
const genStyle: GenerateStyle<FullToken<'Typography'>> = (token) => {
const { componentCls } = token;
return {
[componentCls]: {
fontSize: 'inherit',
[`&${DOT_PREFIX}`]: {
background,
backgroundClip: 'text',
WebkitBackgroundClip: 'text',
color: 'transparent',
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(
['Typography', 'techThemeText'],
(token) => {
return [genStyle(token)];
},
);
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/ThemeProvider.tsx
|
TypeScript (TSX)
|
import { ConfigProvider } from 'antd';
import useButtonStyle from './styles/buttonStyle';
import useTagStyle from './styles/tagStyle';
import useSwitchStyle from './styles/switchStyle';
import useCheckboxStyle from './styles/checkboxStyle';
import useRadioStyle from './styles/radioStyle';
import useSpinStyle from './styles/spinStyle';
import useDividerStyle from './styles/dividerStyle';
import useCardStyle from './styles/cardStyle';
import * as React from 'react';
import { PREFIX } from './constant';
export interface ThemeProviderProps {
disabled?: boolean;
children?: React.ReactNode;
}
export default function ThemeProvider(props: ThemeProviderProps) {
const { children, disabled } = props;
const { getPrefixCls } = React.useContext(ConfigProvider.ConfigContext);
// Button
useButtonStyle(getPrefixCls(`btn`));
// Tag
useTagStyle(getPrefixCls(`tag`));
// Switch
useSwitchStyle(getPrefixCls(`switch`));
// Checkbox
useCheckboxStyle(getPrefixCls(`checkbox`));
// Radio
useRadioStyle(getPrefixCls(`radio`));
// Spin
useSpinStyle(getPrefixCls(`spin`));
// Divider
useDividerStyle(getPrefixCls(`divider`));
// Card
useCardStyle(getPrefixCls(`card`));
// ====================== Render ======================
const passedCls = disabled ? null : PREFIX;
return (
<ConfigProvider
button={{ className: passedCls }}
tag={{ className: passedCls }}
switch={{ className: passedCls }}
typography={{ className: passedCls }}
checkbox={{ className: passedCls }}
radio={{ className: passedCls }}
spin={{ className: passedCls }}
divider={{ className: passedCls }}
card={{ className: passedCls }}
>
{children}
</ConfigProvider>
);
}
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/constant.ts
|
TypeScript
|
export const PREFIX = 'tech-theme';
export const DOT_PREFIX = `.${PREFIX}`;
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/index.tsx
|
TypeScript (TSX)
|
import ThemeProvider from './ThemeProvider';
import Text from './Text';
export { ThemeProvider, Text };
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/buttonStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import {
getAnimationBackground,
getBackgroundAnimation,
getBorderStyle,
} from './gradientUtil';
import { DOT_PREFIX } from '../constant';
// ============================== Border ==============================
const genBorderStyle: GenerateStyle<FullToken<'Button'>> = (token) => {
const { componentCls, lineWidth } = token;
const backgroundAnimation = getBackgroundAnimation(lineWidth);
return {
[`${componentCls}${DOT_PREFIX}`]: {
// ======================= Primary =======================
[`&${componentCls}-primary`]: {
[`&:not(${componentCls}-dangerous)`]: {
...getAnimationBackground(lineWidth),
...backgroundAnimation,
'&:disabled': {
opacity: token.opacityLoading,
color: token.colorTextLightSolid,
},
},
},
// ======================= Default =======================
[`&${componentCls}-default`]: {
[`&:not(${componentCls}-dangerous)`]: {
'&:before': getBorderStyle(lineWidth),
'&:not(:disabled):hover': {
color: token.colorTextLightSolid,
},
'&:disabled:before': {
opacity: token.opacityLoading,
},
},
},
// ======================== Hover ========================
[`&${componentCls}-primary, &${componentCls}-default`]: {
[`&:not(:disabled):not(${componentCls}-dangerous)`]: {
'&:hover': {
filter: `brightness(120%)`,
},
'&:active': {
filter: `brightness(80%)`,
},
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Button', 'techTheme'], (token) => {
return [genBorderStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/cardStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import { getBorderStyle } from './gradientUtil';
import { DOT_PREFIX } from '../constant';
// ============================== Border ==============================
const genStyle: GenerateStyle<FullToken<'Card'>> = (token) => {
const { componentCls, lineWidth } = token;
return {
[`${componentCls}${DOT_PREFIX}`]: {
'&:before': getBorderStyle(lineWidth),
[`${componentCls}-head`]: {
position: 'relative',
'&:before': [
...getBorderStyle(lineWidth),
{
transition: 'none',
},
],
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Card', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/checkboxStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import { background, getBorderStyle } from './gradientUtil';
import { DOT_PREFIX } from '../constant';
// ============================== Border ==============================
export const genStyle: GenerateStyle<
FullToken<'Checkbox'> | FullToken<'Radio'>
> = (token) => {
const { componentCls, lineWidth } = token;
return {
[`${DOT_PREFIX}${componentCls}-wrapper`]: {
[componentCls]: {
'&:before': [
...getBorderStyle(lineWidth),
{
inset: 0,
},
],
[`&${componentCls}-checked ${componentCls}-inner`]: {
background: `${background} !important`,
},
},
'&-disabled': {
[componentCls]: {
'&:before': {
opacity: token.opacityLoading,
},
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Checkbox', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/dividerStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import { background } from './gradientUtil';
import { DOT_PREFIX } from '../constant';
// ============================== Border ==============================
const genStyle: GenerateStyle<FullToken<'Divider'>> = (token) => {
const { componentCls, lineWidth } = token;
return {
[`${DOT_PREFIX}${componentCls}`]: {
[`&${componentCls}-horizontal`]: {
border: 'none',
height: lineWidth,
background,
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Divider', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/gradientUtil.ts
|
TypeScript
|
import { Keyframes } from '@ant-design/cssinjs';
import type { CSSObject } from '@ant-design/cssinjs';
export const background = `linear-gradient(135deg, ${[
'#f7797d',
'#c471ed 35%',
'#12c2e9',
].join(',')})`;
export const getBackground = (lineWidth: number = 0) => ({
background,
backgroundSize: `calc(100% + ${lineWidth * 2}px) calc(100% + ${
lineWidth * 2
}px)`,
backgroundPosition: `-${lineWidth}px -${lineWidth}px`,
});
export const animationBackground = `linear-gradient(-45deg, ${[
'#f7797d',
'#c471ed 24%',
'#12c2e9 48%',
'#12c2e9 52%',
'#c471ed 76%',
'#f7797d',
].join(',')})`;
export const getAnimationBackground = (lineWidth: number = 0): CSSObject => ({
backgroundImage: animationBackground,
backgroundSize: `calc(200% + ${lineWidth * 4}px) calc(200% + ${
lineWidth * 4
}px)`,
backgroundPosition: `-${lineWidth}px -${lineWidth}px`,
});
export const borderMask = [
`linear-gradient(#fff 0 0) content-box`,
`linear-gradient(#fff 0 0)`,
].join(',');
export const getBackgroundAnimation = (lineWidth: number = 0) => {
const rotateKeyframes = new Keyframes('gradient-rotate', {
'50%': {
backgroundPosition: `calc(100% + ${lineWidth}px) -${lineWidth}px`,
},
});
const backgroundAnimation: CSSObject = {
animationName: rotateKeyframes,
animationDuration: '10s',
animationIterationCount: 'infinite',
};
return backgroundAnimation;
};
export const getBorderStyle = (lineWidth: number = 0): CSSObject[] => [
{
content: '""',
position: 'absolute',
inset: -lineWidth,
padding: lineWidth,
borderRadius: 'inherit',
background,
zIndex: 1,
transition: 'all 0.3s',
display: 'block',
pointerEvents: 'none',
mask: borderMask,
maskComposite: `xor`,
WebkitMask: borderMask,
WebkitMaskComposite: 'exclude',
},
{
WebkitMaskComposite: `xor`,
},
];
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/radioStyle.ts
|
TypeScript
|
import { genComponentStyleHook } from './styleUtil';
import { genStyle } from './checkboxStyle';
// ============================== Export ==============================
export default genComponentStyleHook(['Radio', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/spinStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import { background } from './gradientUtil';
import { DOT_PREFIX } from '../constant';
const DOT_COUNT = 9;
const DOT_DIST = 40;
const DOT_MIN_SIZE = 0;
const DOT_MAX_SIZE = 10;
// ============================== Border ==============================
const genStyle: GenerateStyle<FullToken<'Spin'>> = (token) => {
const { componentCls } = token;
const getCircle = (pos: string, sizePtg: number) =>
`radial-gradient(circle at ${pos}, #fff 0, #fff ${sizePtg}%, transparent ${sizePtg}%)`;
const mask = new Array(DOT_COUNT)
.fill(null)
.map((_, index) => {
const angle = index * (360 / DOT_COUNT);
const size =
DOT_MIN_SIZE + (DOT_MAX_SIZE - DOT_MIN_SIZE) * (index / DOT_COUNT);
const pos = [
`${50 + Math.sin((angle * Math.PI) / 180) * DOT_DIST}%`,
`${50 - Math.cos((angle * Math.PI) / 180) * DOT_DIST}%`,
].join(' ');
return getCircle(pos, size);
})
.join(',');
return {
[`${componentCls}${DOT_PREFIX}`]: {
// Hide dot item
[`${componentCls}-dot-item`]: {
display: 'none',
},
// Customize effect
[`${componentCls}-dot`]: {
backgroundImage: background,
mask,
WebkitMask: mask,
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Spin', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/styleUtil.ts
|
TypeScript
|
export * from 'antd/es/theme/internal';
import { theme as Theme, ConfigProvider, GlobalToken } from 'antd';
import { CSSInterpolation, useStyleRegister } from '@ant-design/cssinjs';
import {
FullToken,
OverrideComponent,
} from 'antd/es/theme/util/genComponentStyleHook';
import React from 'react';
// Copy from antd `genComponentStyleHook`, you can use any other CSS-in-JS library instead.
export function genComponentStyleHook<ComponentName extends OverrideComponent>(
componentNames: [ComponentName, string],
styleFn: (token: GlobalToken) => CSSInterpolation,
) {
const concatComponent = componentNames.join('-');
return (prefixCls: string): void => {
const { theme, token, hashId } = Theme.useToken();
const { getPrefixCls, iconPrefixCls } = React.useContext(
ConfigProvider.ConfigContext,
);
const rootPrefixCls = getPrefixCls();
// Shared config
const sharedConfig: Omit<Parameters<typeof useStyleRegister>[0], 'path'> = {
theme,
token,
hashId,
};
useStyleRegister(
{ ...sharedConfig, path: [concatComponent, prefixCls, iconPrefixCls] },
() => {
const componentCls = `.${prefixCls}`;
const mergedToken = {
...token,
componentCls,
prefixCls,
iconCls: `.${iconPrefixCls}`,
antCls: `.${rootPrefixCls}`,
};
const styleInterpolation = styleFn(
mergedToken as any as FullToken<ComponentName>,
);
return styleInterpolation;
},
);
};
}
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/switchStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import { background } from './gradientUtil';
import { DOT_PREFIX } from '../constant';
// ============================== Border ==============================
const genStyle: GenerateStyle<FullToken<'Switch'>> = (token) => {
const { componentCls } = token;
return {
[`${componentCls}${DOT_PREFIX}`]: {
[`&${componentCls}&${componentCls}-checked`]: {
'&, &:hover, &:focus': {
background: `${background} !important`,
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Switch', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/styles/tagStyle.ts
|
TypeScript
|
import {
type GenerateStyle,
genComponentStyleHook,
type FullToken,
} from './styleUtil';
import { getBackground, getBorderStyle } from './gradientUtil';
// ============================== Border ==============================
const genStyle: GenerateStyle<FullToken<'Tag'>> = (token) => {
const { componentCls, lineWidth } = token;
return {
// TODO: CheckableTag missing CP className
[componentCls]: {
[`&:not(${componentCls}-checkable)`]: {
'&:before': getBorderStyle(lineWidth),
},
[`&${componentCls}-checkable`]: {
borderColor: 'transparent !important',
background: token.colorBgContainerDisabled,
backgroundPosition: `-${lineWidth}px -${lineWidth}px`,
transition: 'all 0.3s',
[`&-checked`]: {
...getBackground(lineWidth),
},
'&:hover': {
color: token.colorTextLightSolid,
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook(['Tag', 'techTheme'], (token) => {
return [genStyle(token)];
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
tests/index.test.tsx
|
TypeScript (TSX)
|
import { act, fireEvent, render } from '@testing-library/react';
import { Button } from 'antd';
import { spyElementPrototype } from 'rc-util/lib/test/domHook';
import * as React from 'react';
import { ThemeProvider } from '../src';
describe('HappyWork', () => {
beforeAll(() => {
spyElementPrototype(HTMLElement, 'offsetParent', {
get: () => document.body,
});
});
beforeEach(() => {
document.body.innerHTML = '';
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
jest.useRealTimers();
});
});
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
tests/setup.js
|
JavaScript
|
window.requestAnimationFrame = setTimeout;
window.cancelAnimationFrame = clearTimeout;
global.requestAnimationFrame = global.setTimeout;
global.cancelAnimationFrame = global.clearTimeout;
|
zombieJ/antd-geek-theme-sample
| 18
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.base.ts
|
TypeScript
|
/**
* Base webpack config used across other specific configs
*/
import webpack from 'webpack';
import TsconfigPathsPlugins from 'tsconfig-paths-webpack-plugin';
import webpackPaths from './webpack.paths';
import { dependencies as externals } from '../../release/app/package.json';
const configuration: webpack.Configuration = {
externals: [...Object.keys(externals || {})],
stats: 'errors-only',
module: {
rules: [
{
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader',
options: {
// Remove this line to enable type checking in webpack builds
transpileOnly: true,
compilerOptions: {
module: 'nodenext',
moduleResolution: 'nodenext',
},
},
},
},
],
},
output: {
path: webpackPaths.srcPath,
// https://github.com/webpack/webpack/issues/1114
library: { type: 'commonjs2' },
},
/**
* Determine the array of extensions that should be used to resolve modules.
*/
resolve: {
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
modules: [webpackPaths.srcPath, 'node_modules'],
// There is no need to add aliases here, the paths in tsconfig get mirrored
plugins: [new TsconfigPathsPlugins()],
},
plugins: [new webpack.EnvironmentPlugin({ NODE_ENV: 'production' })],
};
export default configuration;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.eslint.ts
|
TypeScript
|
/* eslint import/no-unresolved: off, import/no-self-import: off */
module.exports = require('./webpack.config.renderer.dev').default;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.main.dev.ts
|
TypeScript
|
/**
* Webpack config for development electron main process
*/
import path from 'path';
import webpack from 'webpack';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { merge } from 'webpack-merge';
import checkNodeEnv from '../scripts/check-node-env';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's
// at the dev webpack config is not accidentally run in a production environment
if (process.env.NODE_ENV === 'production') {
checkNodeEnv('development');
}
const configuration: webpack.Configuration = {
devtool: 'inline-source-map',
mode: 'development',
target: 'electron-main',
entry: {
main: path.join(webpackPaths.srcMainPath, 'main.ts'),
preload: path.join(webpackPaths.srcMainPath, 'preload.ts'),
},
output: {
path: webpackPaths.dllPath,
filename: '[name].bundle.dev.js',
library: {
type: 'umd',
},
},
plugins: [
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new BundleAnalyzerPlugin({
analyzerMode: process.env.ANALYZE === 'true' ? 'server' : 'disabled',
analyzerPort: 8888,
}),
new webpack.DefinePlugin({
'process.type': '"browser"',
}),
],
/**
* Disables webpack processing of __dirname and __filename.
* If you run the bundle in node.js it falls back to these values of node.js.
* https://github.com/webpack/webpack/issues/2010
*/
node: {
__dirname: false,
__filename: false,
},
};
export default merge(baseConfig, configuration);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.main.prod.ts
|
TypeScript
|
/**
* Webpack config for production electron main process
*/
import path from 'path';
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import TerserPlugin from 'terser-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
import deleteSourceMaps from '../scripts/delete-source-maps';
checkNodeEnv('production');
deleteSourceMaps();
const configuration: webpack.Configuration = {
devtool: 'source-map',
mode: 'production',
target: 'electron-main',
entry: {
main: path.join(webpackPaths.srcMainPath, 'main.ts'),
preload: path.join(webpackPaths.srcMainPath, 'preload.ts'),
},
output: {
path: webpackPaths.distMainPath,
filename: '[name].js',
library: {
type: 'umd',
},
},
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
}),
],
},
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: process.env.ANALYZE === 'true' ? 'server' : 'disabled',
analyzerPort: 8888,
}),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*/
new webpack.EnvironmentPlugin({
NODE_ENV: 'production',
DEBUG_PROD: false,
START_MINIMIZED: false,
}),
new webpack.DefinePlugin({
'process.type': '"browser"',
}),
],
/**
* Disables webpack processing of __dirname and __filename.
* If you run the bundle in node.js it falls back to these values of node.js.
* https://github.com/webpack/webpack/issues/2010
*/
node: {
__dirname: false,
__filename: false,
},
};
export default merge(baseConfig, configuration);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.preload.dev.ts
|
TypeScript
|
import path from 'path';
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's
// at the dev webpack config is not accidentally run in a production environment
if (process.env.NODE_ENV === 'production') {
checkNodeEnv('development');
}
const configuration: webpack.Configuration = {
devtool: 'inline-source-map',
mode: 'development',
target: 'electron-preload',
entry: path.join(webpackPaths.srcMainPath, 'preload.ts'),
output: {
path: webpackPaths.dllPath,
filename: 'preload.js',
library: {
type: 'umd',
},
},
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: process.env.ANALYZE === 'true' ? 'server' : 'disabled',
}),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*
* By default, use 'development' as NODE_ENV. This can be overriden with
* 'staging', for example, by changing the ENV variables in the npm scripts
*/
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
new webpack.LoaderOptionsPlugin({
debug: true,
}),
],
/**
* Disables webpack processing of __dirname and __filename.
* If you run the bundle in node.js it falls back to these values of node.js.
* https://github.com/webpack/webpack/issues/2010
*/
node: {
__dirname: false,
__filename: false,
},
watch: true,
};
export default merge(baseConfig, configuration);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.renderer.dev.dll.ts
|
TypeScript
|
/**
* Builds the DLL for development electron renderer process
*/
import webpack from 'webpack';
import path from 'path';
import { merge } from 'webpack-merge';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import { dependencies } from '../../package.json';
import checkNodeEnv from '../scripts/check-node-env';
checkNodeEnv('development');
const dist = webpackPaths.dllPath;
const configuration: webpack.Configuration = {
context: webpackPaths.rootPath,
devtool: 'eval',
mode: 'development',
target: 'electron-renderer',
externals: ['fsevents', 'crypto-browserify'],
/**
* Use `module` from `webpack.config.renderer.dev.js`
*/
module: require('./webpack.config.renderer.dev').default.module,
entry: {
renderer: Object.keys(dependencies || {}),
},
output: {
path: dist,
filename: '[name].dev.dll.js',
library: {
name: 'renderer',
type: 'var',
},
},
plugins: [
new webpack.DllPlugin({
path: path.join(dist, '[name].json'),
name: '[name]',
}),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*/
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
new webpack.LoaderOptionsPlugin({
debug: true,
options: {
context: webpackPaths.srcPath,
output: {
path: webpackPaths.dllPath,
},
},
}),
],
};
export default merge(baseConfig, configuration);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.renderer.dev.ts
|
TypeScript
|
import 'webpack-dev-server';
import path from 'path';
import fs from 'fs';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import chalk from 'chalk';
import { merge } from 'webpack-merge';
import { execSync, spawn } from 'child_process';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's
// at the dev webpack config is not accidentally run in a production environment
if (process.env.NODE_ENV === 'production') {
checkNodeEnv('development');
}
const port = process.env.PORT || 1212;
const manifest = path.resolve(webpackPaths.dllPath, 'renderer.json');
const skipDLLs =
module.parent?.filename.includes('webpack.config.renderer.dev.dll') ||
module.parent?.filename.includes('webpack.config.eslint');
/**
* Warn if the DLL is not built
*/
if (
!skipDLLs &&
!(fs.existsSync(webpackPaths.dllPath) && fs.existsSync(manifest))
) {
console.log(
chalk.black.bgYellow.bold(
'The DLL files are missing. Sit back while we build them for you with "npm run build-dll"',
),
);
execSync('npm run postinstall');
}
const configuration: webpack.Configuration = {
devtool: 'inline-source-map',
mode: 'development',
target: ['web', 'electron-renderer'],
entry: [
`webpack-dev-server/client?http://localhost:${port}/dist`,
'webpack/hot/only-dev-server',
path.join(webpackPaths.srcRendererPath, 'index.tsx'),
],
output: {
path: webpackPaths.distRendererPath,
publicPath: '/',
filename: 'renderer.dev.js',
library: {
type: 'umd',
},
},
module: {
rules: [
{
test: /\.s?(c|a)ss$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
},
},
'sass-loader',
],
include: /\.module\.s?(c|a)ss$/,
},
{
test: /\.s?css$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: /\.module\.s?(c|a)ss$/,
},
// Fonts
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
// Images
{
test: /\.(png|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
// SVG
{
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: false,
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
titleProp: true,
ref: true,
},
},
'file-loader',
],
},
],
},
plugins: [
...(skipDLLs
? []
: [
new webpack.DllReferencePlugin({
context: webpackPaths.dllPath,
manifest: require(manifest),
sourceType: 'var',
}),
]),
new webpack.NoEmitOnErrorsPlugin(),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*
* By default, use 'development' as NODE_ENV. This can be overriden with
* 'staging', for example, by changing the ENV variables in the npm scripts
*/
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
new webpack.LoaderOptionsPlugin({
debug: true,
}),
new ReactRefreshWebpackPlugin(),
new HtmlWebpackPlugin({
filename: path.join('index.html'),
template: path.join(webpackPaths.srcRendererPath, 'index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
},
isBrowser: false,
env: process.env.NODE_ENV,
isDevelopment: process.env.NODE_ENV !== 'production',
nodeModules: webpackPaths.appNodeModulesPath,
}),
],
node: {
__dirname: false,
__filename: false,
},
devServer: {
port,
compress: true,
hot: true,
headers: { 'Access-Control-Allow-Origin': '*' },
static: {
publicPath: '/',
},
historyApiFallback: {
verbose: true,
},
setupMiddlewares(middlewares) {
console.log('Starting preload.js builder...');
const preloadProcess = spawn('npm', ['run', 'start:preload'], {
shell: true,
stdio: 'inherit',
})
.on('close', (code: number) => process.exit(code!))
.on('error', (spawnError) => console.error(spawnError));
console.log('Starting Main Process...');
let args = ['run', 'start:main'];
if (process.env.MAIN_ARGS) {
args = args.concat(
['--', ...process.env.MAIN_ARGS.matchAll(/"[^"]+"|[^\s"]+/g)].flat(),
);
}
spawn('npm', args, {
shell: true,
stdio: 'inherit',
})
.on('close', (code: number) => {
preloadProcess.kill();
process.exit(code!);
})
.on('error', (spawnError) => console.error(spawnError));
return middlewares;
},
},
};
export default merge(baseConfig, configuration);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.config.renderer.prod.ts
|
TypeScript
|
/**
* Build config for electron renderer process
*/
import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import { merge } from 'webpack-merge';
import TerserPlugin from 'terser-webpack-plugin';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
import deleteSourceMaps from '../scripts/delete-source-maps';
checkNodeEnv('production');
deleteSourceMaps();
const configuration: webpack.Configuration = {
devtool: 'source-map',
mode: 'production',
target: ['web', 'electron-renderer'],
entry: [path.join(webpackPaths.srcRendererPath, 'index.tsx')],
output: {
path: webpackPaths.distRendererPath,
publicPath: './',
filename: 'renderer.js',
library: {
type: 'umd',
},
},
module: {
rules: [
{
test: /\.s?(a|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
},
},
'sass-loader',
],
include: /\.module\.s?(c|a)ss$/,
},
{
test: /\.s?(a|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
exclude: /\.module\.s?(c|a)ss$/,
},
// Fonts
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
// Images
{
test: /\.(png|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
// SVG
{
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: false,
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
titleProp: true,
ref: true,
},
},
'file-loader',
],
},
],
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin(), new CssMinimizerPlugin()],
},
plugins: [
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*/
new webpack.EnvironmentPlugin({
NODE_ENV: 'production',
DEBUG_PROD: false,
}),
new MiniCssExtractPlugin({
filename: 'style.css',
}),
new BundleAnalyzerPlugin({
analyzerMode: process.env.ANALYZE === 'true' ? 'server' : 'disabled',
analyzerPort: 8889,
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.join(webpackPaths.srcRendererPath, 'index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
},
isBrowser: false,
isDevelopment: false,
}),
new webpack.DefinePlugin({
'process.type': '"renderer"',
}),
],
};
export default merge(baseConfig, configuration);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/configs/webpack.paths.ts
|
TypeScript
|
const path = require('path');
const rootPath = path.join(__dirname, '../..');
const erbPath = path.join(__dirname, '..');
const erbNodeModulesPath = path.join(erbPath, 'node_modules');
const dllPath = path.join(__dirname, '../dll');
const srcPath = path.join(rootPath, 'src');
const srcMainPath = path.join(srcPath, 'main');
const srcRendererPath = path.join(srcPath, 'renderer');
const releasePath = path.join(rootPath, 'release');
const appPath = path.join(releasePath, 'app');
const appPackagePath = path.join(appPath, 'package.json');
const appNodeModulesPath = path.join(appPath, 'node_modules');
const srcNodeModulesPath = path.join(srcPath, 'node_modules');
const distPath = path.join(appPath, 'dist');
const distMainPath = path.join(distPath, 'main');
const distRendererPath = path.join(distPath, 'renderer');
const buildPath = path.join(releasePath, 'build');
export default {
rootPath,
erbNodeModulesPath,
dllPath,
srcPath,
srcMainPath,
srcRendererPath,
releasePath,
appPath,
appPackagePath,
appNodeModulesPath,
srcNodeModulesPath,
distPath,
distMainPath,
distRendererPath,
buildPath,
};
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/mocks/fileMock.js
|
JavaScript
|
export default 'test-file-stub';
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/check-build-exists.ts
|
TypeScript
|
// Check if the renderer and main bundles are built
import path from 'path';
import chalk from 'chalk';
import fs from 'fs';
import { TextEncoder, TextDecoder } from 'node:util';
import webpackPaths from '../configs/webpack.paths';
const mainPath = path.join(webpackPaths.distMainPath, 'main.js');
const rendererPath = path.join(webpackPaths.distRendererPath, 'renderer.js');
if (!fs.existsSync(mainPath)) {
throw new Error(
chalk.whiteBright.bgRed.bold(
'The main process is not built yet. Build it by running "npm run build:main"',
),
);
}
if (!fs.existsSync(rendererPath)) {
throw new Error(
chalk.whiteBright.bgRed.bold(
'The renderer process is not built yet. Build it by running "npm run build:renderer"',
),
);
}
// JSDOM does not implement TextEncoder and TextDecoder
if (!global.TextEncoder) {
global.TextEncoder = TextEncoder;
}
if (!global.TextDecoder) {
// @ts-ignore
global.TextDecoder = TextDecoder;
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/check-native-dep.js
|
JavaScript
|
import fs from 'fs';
import chalk from 'chalk';
import { execSync } from 'child_process';
import { dependencies } from '../../package.json';
if (dependencies) {
const dependenciesKeys = Object.keys(dependencies);
const nativeDeps = fs
.readdirSync('node_modules')
.filter((folder) => fs.existsSync(`node_modules/${folder}/binding.gyp`));
if (nativeDeps.length === 0) {
process.exit(0);
}
try {
// Find the reason for why the dependency is installed. If it is installed
// because of a devDependency then that is okay. Warn when it is installed
// because of a dependency
const { dependencies: dependenciesObject } = JSON.parse(
execSync(`npm ls ${nativeDeps.join(' ')} --json`).toString(),
);
const rootDependencies = Object.keys(dependenciesObject);
const filteredRootDependencies = rootDependencies.filter((rootDependency) =>
dependenciesKeys.includes(rootDependency),
);
if (filteredRootDependencies.length > 0) {
const plural = filteredRootDependencies.length > 1;
console.log(`
${chalk.whiteBright.bgYellow.bold(
'Webpack does not work with native dependencies.',
)}
${chalk.bold(filteredRootDependencies.join(', '))} ${
plural ? 'are native dependencies' : 'is a native dependency'
} and should be installed inside of the "./release/app" folder.
First, uninstall the packages from "./package.json":
${chalk.whiteBright.bgGreen.bold('npm uninstall your-package')}
${chalk.bold(
'Then, instead of installing the package to the root "./package.json":',
)}
${chalk.whiteBright.bgRed.bold('npm install your-package')}
${chalk.bold('Install the package to "./release/app/package.json"')}
${chalk.whiteBright.bgGreen.bold(
'cd ./release/app && npm install your-package',
)}
Read more about native dependencies at:
${chalk.bold(
'https://electron-react-boilerplate.js.org/docs/adding-dependencies/#module-structure',
)}
`);
process.exit(1);
}
} catch {
console.log('Native dependencies could not be checked');
}
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/check-node-env.js
|
JavaScript
|
import chalk from 'chalk';
export default function checkNodeEnv(expectedEnv) {
if (!expectedEnv) {
throw new Error('"expectedEnv" not set');
}
if (process.env.NODE_ENV !== expectedEnv) {
console.log(
chalk.whiteBright.bgRed.bold(
`"process.env.NODE_ENV" must be "${expectedEnv}" to use this webpack config`,
),
);
process.exit(2);
}
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/check-port-in-use.js
|
JavaScript
|
import chalk from 'chalk';
import detectPort from 'detect-port';
const port = process.env.PORT || '1212';
detectPort(port, (_err, availablePort) => {
if (port !== String(availablePort)) {
throw new Error(
chalk.whiteBright.bgRed.bold(
`Port "${port}" on "localhost" is already in use. Please use another port. ex: PORT=4343 npm start`,
),
);
} else {
process.exit(0);
}
});
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/clean.js
|
JavaScript
|
import { rimrafSync } from 'rimraf';
import fs from 'fs';
import webpackPaths from '../configs/webpack.paths';
const foldersToRemove = [
webpackPaths.distPath,
webpackPaths.buildPath,
webpackPaths.dllPath,
];
foldersToRemove.forEach((folder) => {
if (fs.existsSync(folder)) rimrafSync(folder);
});
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/delete-source-maps.js
|
JavaScript
|
import fs from 'fs';
import path from 'path';
import { rimrafSync } from 'rimraf';
import webpackPaths from '../configs/webpack.paths';
export default function deleteSourceMaps() {
if (fs.existsSync(webpackPaths.distMainPath))
rimrafSync(path.join(webpackPaths.distMainPath, '*.js.map'), {
glob: true,
});
if (fs.existsSync(webpackPaths.distRendererPath))
rimrafSync(path.join(webpackPaths.distRendererPath, '*.js.map'), {
glob: true,
});
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/electron-rebuild.js
|
JavaScript
|
import { execSync } from 'child_process';
import fs from 'fs';
import { dependencies } from '../../release/app/package.json';
import webpackPaths from '../configs/webpack.paths';
if (
Object.keys(dependencies || {}).length > 0 &&
fs.existsSync(webpackPaths.appNodeModulesPath)
) {
const electronRebuildCmd =
'../../node_modules/.bin/electron-rebuild --force --types prod,dev,optional --module-dir .';
const cmd =
process.platform === 'win32'
? electronRebuildCmd.replace(/\//g, '\\')
: electronRebuildCmd;
execSync(cmd, {
cwd: webpackPaths.appPath,
stdio: 'inherit',
});
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/link-modules.ts
|
TypeScript
|
import fs from 'fs';
import webpackPaths from '../configs/webpack.paths';
const { srcNodeModulesPath, appNodeModulesPath, erbNodeModulesPath } =
webpackPaths;
if (fs.existsSync(appNodeModulesPath)) {
if (!fs.existsSync(srcNodeModulesPath)) {
fs.symlinkSync(appNodeModulesPath, srcNodeModulesPath, 'junction');
}
if (!fs.existsSync(erbNodeModulesPath)) {
fs.symlinkSync(appNodeModulesPath, erbNodeModulesPath, 'junction');
}
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.erb/scripts/notarize.js
|
JavaScript
|
const { notarize } = require('@electron/notarize');
const { build } = require('../../package.json');
exports.default = async function notarizeMacos(context) {
const { electronPlatformName, appOutDir } = context;
if (electronPlatformName !== 'darwin') {
return;
}
if (process.env.CI !== 'true') {
console.warn('Skipping notarizing step. Packaging is not running in CI');
return;
}
if (
!(
'APPLE_ID' in process.env &&
'APPLE_ID_PASS' in process.env &&
'APPLE_TEAM_ID' in process.env
)
) {
console.warn(
'Skipping notarizing step. APPLE_ID, APPLE_ID_PASS, and APPLE_TEAM_ID env variables must be set',
);
return;
}
const appName = context.packager.appInfo.productFilename;
await notarize({
tool: 'notarytool',
appBundleId: build.appId,
appPath: `${appOutDir}/${appName}.app`,
appleId: process.env.APPLE_ID,
appleIdPassword: process.env.APPLE_ID_PASS,
teamId: process.env.APPLE_TEAM_ID,
});
};
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.eslintrc.js
|
JavaScript
|
module.exports = {
extends: 'erb',
plugins: ['@typescript-eslint', 'promise'],
rules: {
// A temporary hack related to IDE not resolving correct package.json
'import/no-extraneous-dependencies': 'off',
'react/react-in-jsx-scope': 'off',
'react/jsx-filename-extension': 'off',
'import/extensions': 'off',
'import/no-unresolved': 'off',
'import/no-import-module-exports': 'off',
'import/order': 'off',
'no-shadow': 'off',
'@typescript-eslint/no-shadow': 'error',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'consistent-return': 'off',
'react/function-component-definition': 'off',
'react/jsx-props-no-spreading': 'off',
'react-hooks/exhaustive-deps': 'off',
'react/no-array-index-key': 'off',
'react/require-default-props': 'off',
'react/destructuring-assignment': 'off',
'promise/always-return': 'off',
},
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module',
},
settings: {
'import/resolver': {
// See https://github.com/benmosher/eslint-plugin-import/issues/1396#issuecomment-575727774 for line below
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
moduleDirectory: ['node_modules', 'src/'],
},
webpack: {
config: require.resolve('./.erb/configs/webpack.config.eslint.ts'),
},
typescript: {},
},
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx'],
},
},
};
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
assets/assets.d.ts
|
TypeScript
|
type Styles = Record<string, string>;
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
const content: string;
export default content;
}
declare module '*.png' {
const content: string;
export default content;
}
declare module '*.jpg' {
const content: string;
export default content;
}
declare module '*.scss' {
const content: Styles;
export default content;
}
declare module '*.sass' {
const content: Styles;
export default content;
}
declare module '*.css' {
const content: Styles;
export default content;
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/__tests__/App.test.tsx
|
TypeScript (TSX)
|
import '@testing-library/jest-dom';
import { render } from '@testing-library/react';
import App from '../renderer/App';
describe('App', () => {
it('should render', () => {
expect(render(<App />)).toBeTruthy();
});
});
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/main/main.ts
|
TypeScript
|
/* eslint global-require: off, no-console: off, promise/always-return: off */
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, shell, ipcMain } from 'electron';
import { autoUpdater } from 'electron-updater';
import log from 'electron-log';
import MenuBuilder from './menu';
import { resolveHtmlPath } from './util';
class AppUpdater {
constructor() {
log.transports.file.level = 'info';
autoUpdater.logger = log;
autoUpdater.checkForUpdatesAndNotify();
}
}
let mainWindow: BrowserWindow | null = null;
ipcMain.on('ipc-example', async (event, arg) => {
const msgTemplate = (pingPong: string) => `IPC test: ${pingPong}`;
console.log(msgTemplate(arg));
event.reply('ipc-example', msgTemplate('pong'));
});
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
if (isDebug) {
require('electron-debug').default();
}
const installExtensions = async () => {
const installer = require('electron-devtools-installer');
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
const extensions = ['REACT_DEVELOPER_TOOLS'];
return installer
.default(
extensions.map((name) => installer[name]),
forceDownload,
)
.catch(console.log);
};
const createWindow = async () => {
if (isDebug) {
// TODO: 网络不好,加载不了。解决这个问题。
// await installExtensions();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
mainWindow = new BrowserWindow({
show: false,
width: 1200,
height: 728,
icon: getAssetPath('icon.png'),
webPreferences: {
webSecurity: false, // 禁用web安全策略以解决CORS问题
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('ready-to-show', () => {
if (!mainWindow) {
throw new Error('"mainWindow" is not defined');
}
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
} else {
mainWindow.show();
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
const menuBuilder = new MenuBuilder(mainWindow);
menuBuilder.buildMenu();
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
// Remove this if your app does not use auto updates
// eslint-disable-next-line
new AppUpdater();
};
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) createWindow();
});
})
.catch(console.log);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/main/menu.ts
|
TypeScript
|
import {
app,
Menu,
shell,
BrowserWindow,
MenuItemConstructorOptions,
} from 'electron';
interface DarwinMenuItemConstructorOptions extends MenuItemConstructorOptions {
selector?: string;
submenu?: DarwinMenuItemConstructorOptions[] | Menu;
}
export default class MenuBuilder {
mainWindow: BrowserWindow;
constructor(mainWindow: BrowserWindow) {
this.mainWindow = mainWindow;
}
buildMenu(): Menu {
if (
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
) {
this.setupDevelopmentEnvironment();
}
const template =
process.platform === 'darwin'
? this.buildDarwinTemplate()
: this.buildDefaultTemplate();
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
return menu;
}
setupDevelopmentEnvironment(): void {
this.mainWindow.webContents.on('context-menu', (_, props) => {
const { x, y } = props;
Menu.buildFromTemplate([
{
label: 'Inspect element',
click: () => {
this.mainWindow.webContents.inspectElement(x, y);
},
},
]).popup({ window: this.mainWindow });
});
}
buildDarwinTemplate(): MenuItemConstructorOptions[] {
const subMenuAbout: DarwinMenuItemConstructorOptions = {
label: 'Electron',
submenu: [
{
label: 'About ElectronReact',
selector: 'orderFrontStandardAboutPanel:',
},
{ type: 'separator' },
{ label: 'Services', submenu: [] },
{ type: 'separator' },
{
label: 'Hide ElectronReact',
accelerator: 'Command+H',
selector: 'hide:',
},
{
label: 'Hide Others',
accelerator: 'Command+Shift+H',
selector: 'hideOtherApplications:',
},
{ label: 'Show All', selector: 'unhideAllApplications:' },
{ type: 'separator' },
{
label: 'Quit',
accelerator: 'Command+Q',
click: () => {
app.quit();
},
},
],
};
const subMenuEdit: DarwinMenuItemConstructorOptions = {
label: 'Edit',
submenu: [
{ label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' },
{ label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' },
{ type: 'separator' },
{ label: 'Cut', accelerator: 'Command+X', selector: 'cut:' },
{ label: 'Copy', accelerator: 'Command+C', selector: 'copy:' },
{ label: 'Paste', accelerator: 'Command+V', selector: 'paste:' },
{
label: 'Select All',
accelerator: 'Command+A',
selector: 'selectAll:',
},
],
};
const subMenuViewDev: MenuItemConstructorOptions = {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Command+R',
click: () => {
this.mainWindow.webContents.reload();
},
},
{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click: () => {
this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
},
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Command+I',
click: () => {
this.mainWindow.webContents.toggleDevTools();
},
},
],
};
const subMenuViewProd: MenuItemConstructorOptions = {
label: 'View',
submenu: [
{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click: () => {
this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
},
},
],
};
const subMenuWindow: DarwinMenuItemConstructorOptions = {
label: 'Window',
submenu: [
{
label: 'Minimize',
accelerator: 'Command+M',
selector: 'performMiniaturize:',
},
{ label: 'Close', accelerator: 'Command+W', selector: 'performClose:' },
{ type: 'separator' },
{ label: 'Bring All to Front', selector: 'arrangeInFront:' },
],
};
const subMenuHelp: MenuItemConstructorOptions = {
label: 'Help',
submenu: [
{
label: 'Learn More',
click() {
shell.openExternal('https://electronjs.org');
},
},
{
label: 'Documentation',
click() {
shell.openExternal(
'https://github.com/electron/electron/tree/main/docs#readme',
);
},
},
{
label: 'Community Discussions',
click() {
shell.openExternal('https://www.electronjs.org/community');
},
},
{
label: 'Search Issues',
click() {
shell.openExternal('https://github.com/electron/electron/issues');
},
},
],
};
const subMenuView =
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
? subMenuViewDev
: subMenuViewProd;
return [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp];
}
buildDefaultTemplate() {
const templateDefault = [
{
label: '&File',
submenu: [
{
label: '&Open',
accelerator: 'Ctrl+O',
},
{
label: '&Close',
accelerator: 'Ctrl+W',
click: () => {
this.mainWindow.close();
},
},
],
},
{
label: '&View',
submenu:
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
? [
{
label: '&Reload',
accelerator: 'Ctrl+R',
click: () => {
this.mainWindow.webContents.reload();
},
},
{
label: 'Toggle &Full Screen',
accelerator: 'F11',
click: () => {
this.mainWindow.setFullScreen(
!this.mainWindow.isFullScreen(),
);
},
},
{
label: 'Toggle &Developer Tools',
accelerator: 'Alt+Ctrl+I',
click: () => {
this.mainWindow.webContents.toggleDevTools();
},
},
]
: [
{
label: 'Toggle &Full Screen',
accelerator: 'F11',
click: () => {
this.mainWindow.setFullScreen(
!this.mainWindow.isFullScreen(),
);
},
},
],
},
{
label: 'Help',
submenu: [
{
label: 'Learn More',
click() {
shell.openExternal('https://electronjs.org');
},
},
{
label: 'Documentation',
click() {
shell.openExternal(
'https://github.com/electron/electron/tree/main/docs#readme',
);
},
},
{
label: 'Community Discussions',
click() {
shell.openExternal('https://www.electronjs.org/community');
},
},
{
label: 'Search Issues',
click() {
shell.openExternal('https://github.com/electron/electron/issues');
},
},
],
},
];
return templateDefault;
}
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/main/preload.ts
|
TypeScript
|
// Disable no-unused-vars, broken for spread args
/* eslint no-unused-vars: off */
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
export type Channels = 'ipc-example';
const electronHandler = {
ipcRenderer: {
sendMessage(channel: Channels, ...args: unknown[]) {
ipcRenderer.send(channel, ...args);
},
on(channel: Channels, func: (...args: unknown[]) => void) {
const subscription = (_event: IpcRendererEvent, ...args: unknown[]) =>
func(...args);
ipcRenderer.on(channel, subscription);
return () => {
ipcRenderer.removeListener(channel, subscription);
};
},
once(channel: Channels, func: (...args: unknown[]) => void) {
ipcRenderer.once(channel, (_event, ...args) => func(...args));
},
},
};
contextBridge.exposeInMainWorld('electron', electronHandler);
export type ElectronHandler = typeof electronHandler;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/main/util.ts
|
TypeScript
|
/* eslint import/prefer-default-export: off */
import { URL } from 'url';
import path from 'path';
export function resolveHtmlPath(htmlFileName: string) {
if (process.env.NODE_ENV === 'development') {
const port = process.env.PORT || 1212;
const url = new URL(`http://localhost:${port}`);
url.pathname = htmlFileName;
return url.href;
}
return `file://${path.resolve(__dirname, '../renderer/', htmlFileName)}`;
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/App.css
|
CSS
|
@import '~antd/dist/reset.css';
html {
}
body::before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background: linear-gradient(
200.96deg,
#fedc2a -29.09%,
#dd5789 51.77%,
#7a2c9e 129.35%
);
}
root {
width: 100%;
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/App.tsx
|
TypeScript (TSX)
|
import { MemoryRouter as Router, Routes, Route } from 'react-router-dom';
import { App as AntdApp } from 'antd';
import './App.css';
import HomePage from './HomePage';
import SetupPage from './SetupPage';
import useHA, { HAContext } from './useHA';
export default function App() {
const instance = useHA();
return (
<HAContext.Provider value={instance}>
<AntdApp>
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/setup" element={<SetupPage />} />
</Routes>
</Router>
</AntdApp>
</HAContext.Provider>
);
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/HomePage.tsx
|
TypeScript (TSX)
|
import React, { useEffect, useContext, JSX } from 'react';
import { Form, Input, Button, Card, Typography, App } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { HAContext } from './useHA';
const { Title } = Typography;
interface HomeAssistantFormValues {
address: string;
token: string;
}
function HomePage(): JSX.Element {
const { message } = App.useApp();
const [form] = Form.useForm();
const haInstance = useContext(HAContext);
const navigate = useNavigate();
// 组件加载时从localStorage读取数据
useEffect(() => {
const savedData = localStorage.getItem('homeAssistantConfig');
if (savedData) {
try {
const parsedData = JSON.parse(savedData);
form.setFieldsValue(parsedData);
} catch (error) {
console.error('Failed to parse saved data:', error);
}
}
}, [form]);
// 表单数据变化时保存到localStorage
const onValuesChange = (
changedValues: Partial<HomeAssistantFormValues>,
allValues: HomeAssistantFormValues,
) => {
localStorage.setItem('homeAssistantConfig', JSON.stringify(allValues));
};
// 登录验证函数
const loginToHomeAssistant = async (values: HomeAssistantFormValues) => {
try {
// 使用useHA context的login方法
if (haInstance) {
await haInstance.login(values.address, values.token);
message.success('成功连接到 Home Assistant!');
// 登录成功后跳转到设置页面
navigate('/setup');
} else {
message.error('Home Assistant实例未正确初始化');
}
} catch (error) {
// 网络错误或其他异常
message.error('连接过程中发生错误,请检查网络连接和地址。');
console.error('Login error:', error);
}
};
const onFinish = (values: HomeAssistantFormValues) => {
console.log('Home Assistant Address:', values.address);
console.log('Token:', values.token);
// 调用登录验证函数
loginToHomeAssistant(values);
};
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
}}
>
<Card
style={{
width: 400,
boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
backgroundColor: 'rgba(255, 255, 255, 0.9)',
}}
>
<div style={{ textAlign: 'center', marginBottom: 24 }}>
<HomeOutlined style={{ fontSize: 48, color: '#1890ff' }} />
<Title level={3} style={{ marginTop: 16, marginBottom: 0 }}>
Home Assistant 配置
</Title>
<p style={{ color: '#888' }}>请输入您的 Home Assistant 地址和令牌</p>
</div>
<Form
form={form}
name="homeAssistantForm"
onFinish={onFinish}
layout="vertical"
onValuesChange={onValuesChange}
>
<Form.Item
name="address"
label="地址"
validateFirst
rules={[
{
required: true,
message: '请输入 Home Assistant 的地址!',
},
{
pattern: /^(http|https):\/\/(\d{1,3}\.){3}\d{1,3}:\d{1,5}$/,
message:
'请输入有效的地址格式,例如: http://192.168.50.116:8123',
},
{
validator: (_, value) => {
if (value) {
// 检查是否以 http 或 https 开头
if (
!value.startsWith('http://') &&
!value.startsWith('https://')
) {
return Promise.reject(
new Error('地址必须以 http:// 或 https:// 开头'),
);
}
// 提取主机和端口部分
const urlWithoutProtocol = value.replace(
/^(http|https):\/\//,
'',
);
const parts = urlWithoutProtocol.split(':');
if (parts.length !== 2) {
return Promise.reject(
new Error(
'请输入有效的地址格式,例如: http://192.168.50.116:8123',
),
);
}
const ip = parts[0];
const port = parts[1];
// 验证IP地址
const ipParts = ip.split('.');
if (ipParts.length !== 4) {
return Promise.reject(new Error('请输入有效的IP地址'));
}
ipParts.forEach((part: any) => {
const num = parseInt(part, 10);
if (Number.isNaN(num) || num < 0 || num > 255) {
return Promise.reject(new Error('请输入有效的IP地址'));
}
});
// 验证端口
const portNum = parseInt(port, 10);
if (
Number.isNaN(portNum) ||
portNum < 1 ||
portNum > 65535
) {
return Promise.reject(
new Error('端口号必须在 1-65535 之间'),
);
}
}
return Promise.resolve();
},
},
]}
>
<Input
placeholder="例如: http://192.168.50.116:8123"
size="large"
/>
</Form.Item>
<Form.Item
name="token"
label="令牌"
tooltip="HA界面:左下角进入个人页面 > 右上方点击安全 tab > 滚动到最下面点击创建令牌"
rules={[
{
required: true,
message: '请输入令牌!',
},
]}
>
<Input.TextArea
placeholder="请输入令牌"
size="large"
rows={3}
style={{ resize: 'vertical' }}
/>
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
size="large"
style={{ width: '100%' }}
>
连接
</Button>
</Form.Item>
</Form>
</Card>
</div>
);
}
export default HomePage;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/KNXEditor.tsx
|
TypeScript (TSX)
|
import React, { useEffect } from 'react';
import { Form, Input, Button, Flex, Typography, Divider, Alert } from 'antd';
import { KNXItem } from './types';
function toKNXText(list: KNXItem[] = []) {
return `
knx:
light:
${list
.filter((item) => item && item.name && item.address)
.map((item) =>
[
// KNX dev
` - name: "${item.name}"`,
` address: "${item.address}"`,
` state_address: "${item.address}"`,
].join('\n'),
)
.join('\n')}
`.trim();
}
export interface KNXEditorProps {
onKNXChange?: (items: KNXItem[]) => void;
}
const KNXEditor: React.FC<KNXEditorProps> = ({ onKNXChange }) => {
const [form] = Form.useForm();
const items = Form.useWatch('knxItems', form);
// 初始化时从 localStorage 加载数据
useEffect(() => {
const savedData = localStorage.getItem('knxItems');
if (savedData) {
try {
const knxItems = JSON.parse(savedData);
form.setFieldsValue({ knxItems });
} catch (e) {
console.error('解析 localStorage 数据失败:', e);
}
}
}, [form]);
useEffect(() => {
if (onKNXChange) {
onKNXChange(items);
}
}, [items, onKNXChange]);
// 表单数据变化时保存到 localStorage
const handleValuesChange = () => {
setTimeout(() => {
const values = form.getFieldsValue();
if (values.knxItems) {
localStorage.setItem('knxItems', JSON.stringify(values.knxItems));
}
}, 0);
};
return (
<div>
<Typography>
<pre>
{`
名字:随便起名字,你怎么舒服怎么来。
地址:进入 KNX 网关,访问:192.168.1.200。登录后查看房间,在房间中可以看到灯的列表,点开就有地址。
`.trim()}
</pre>
</Typography>
<Form
form={form}
initialValues={{ knxItems: [] }}
onValuesChange={handleValuesChange}
>
<Form.List name="knxItems">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Flex
key={field.key}
style={{ marginBottom: 8 }}
align="start"
gap="middle"
>
<Form.Item
{...field}
name={[field.name, 'name']}
rules={[{ required: true, message: '请输入名称' }]}
key="name"
style={{ flex: '50%' }}
>
<Input placeholder="名称,如:主卧主灯" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'address']}
rules={[
{ required: true, message: '请输入地址' },
{
pattern: /^\d+\/\d+\/\d+$/,
message: '地址格式应为: 数字/数字/数字,如: 1/1/1',
},
]}
key="address"
style={{ flex: '50%' }}
>
<Input placeholder="地址,如:1/1/1" />
</Form.Item>
<Button
onClick={() => remove(field.name)}
danger
style={{ flex: 'none' }}
>
删除
</Button>
</Flex>
))}
<Form.Item>
<Button
type="dashed"
onClick={() => add()}
style={{ width: '100%', marginTop: 16 }}
>
添加 KNX 设备
</Button>
</Form.Item>
</>
)}
</Form.List>
{/* 生成 KNX 配置 */}
<Divider>configuration.yaml</Divider>
<Alert
message="将数据直接贴到 configuration.yaml 文件最后面(不是覆盖!),重新加载配置首页就会显示房间开关"
type="info"
/>
<Form.Item noStyle shouldUpdate>
{() => {
const list = form.getFieldValue('knxItems');
return (
<Typography>
<pre>{toKNXText(list)}</pre>
</Typography>
);
}}
</Form.Item>
</Form>
</div>
);
};
export default KNXEditor;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/MiBindEditor.tsx
|
TypeScript (TSX)
|
import React, { useContext, useEffect, useState } from 'react';
import { HAContext, HADevice } from '../useHA';
import { message, Spin, Tabs } from 'antd';
import MiBindEditorDebugList from './MiBindEditorDebugList';
import MiBindEditorMapper from './MiBindEditorMapper';
import { KNXItem } from './types';
const { TabPane } = Tabs;
interface MiBindEditorProps {
knxItems: KNXItem[];
}
const MiBindEditor: React.FC<MiBindEditorProps> = ({ knxItems }) => {
const haInstance = useContext(HAContext);
const [devices, setDevices] = useState<HADevice[]>([]);
const [loading, setLoading] = useState(false);
const handleGetDevices = async () => {
try {
setLoading(true);
if (haInstance) {
const nextDevices = await haInstance.getDevices();
// 过滤出 entities 里包含 `switch.` 开头的 devices
const filteredDevices = nextDevices.filter(
(device) =>
device.entities.some((entity) => entity.startsWith('switch.')) &&
device.entities.some((entity) => entity.includes('giot')),
);
console.log('获取到的设备信息:', filteredDevices);
setDevices(filteredDevices);
message.success('成功获取设备信息!');
} else {
message.error('Home Assistant实例未正确初始化');
}
} catch (error) {
console.error('获取设备信息失败:', error);
message.error('获取设备信息失败,请检查连接配置');
} finally {
setLoading(false);
}
};
useEffect(() => {
handleGetDevices();
}, []);
return (
<div>
{loading ? (
<Spin tip="加载中...">
<div style={{ height: 100 }} />
</Spin>
) : (
<Tabs>
<TabPane tab="配对" key="0">
<MiBindEditorMapper devices={devices} knxItems={knxItems} />
</TabPane>
<TabPane tab="调试" key="1">
<MiBindEditorDebugList devices={devices} />
</TabPane>
</Tabs>
)}
</div>
);
};
export default MiBindEditor;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/MiBindEditorDebugList.tsx
|
TypeScript (TSX)
|
import React from 'react';
import { List, Card, Typography } from 'antd';
import { HADevice } from '../useHA';
const { Text } = Typography;
interface MiBindEditorDebugListProps {
devices: HADevice[];
}
const MiBindEditorDebugList: React.FC<MiBindEditorDebugListProps> = ({
devices,
}) => {
return (
<List
dataSource={devices}
renderItem={(device) => (
<List.Item>
<Card title={device.name} size="small" style={{ width: '100%' }}>
<Text type="secondary">ID: {device.deviceId}</Text>
<div style={{ marginTop: 8 }}>
<Text strong>Entities:</Text>
{device.entities.map((entity, index) => (
<div key={index}>
<Text code>{entity}</Text>
</div>
))}
</div>
</Card>
</List.Item>
)}
/>
);
};
export default MiBindEditorDebugList;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/MiBindEditorMapper.tsx
|
TypeScript (TSX)
|
import React, {
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { HAContext, HADevice, HAEntity } from '../useHA';
import { KNXItem } from './types';
import { batchGenScripts } from './util';
import {
Alert,
Form,
Input,
Button,
Flex,
Divider,
Select,
Spin,
Typography,
} from 'antd';
export interface EntityItem {
entityId: string;
deviceId: string;
deviceName: string;
entity?: HAEntity;
}
interface MiBindEditorMapperProps {
devices: HADevice[];
}
function Title(props: { value?: string; entities: any }) {
return (
<div>{props.entities[props.value!]?.entity?.attributes?.friendly_name}</div>
);
}
const MiBindEditorMapper: React.FC<MiBindEditorMapperProps> = ({ devices }) => {
const instance = useContext(HAContext);
const [form] = Form.useForm();
const [entities, setEntities] = useState<Record<string, EntityItem>>({});
const [lightEntityList, setLightEntityList] = useState<HAEntity[]>([]);
useEffect(() => {
// 将 devices 里的数据打平成包含 entityId、deviceId 和 deviceName 的列表
let flattenedEntities: EntityItem[] = devices.flatMap((device) =>
device.entities
.filter((ent) => ent.startsWith('switch.'))
.map((entityId) => ({
entityId,
deviceId: device.deviceId,
deviceName: device.name,
})),
);
// setEntityList(flattenedEntities);
instance?.getEntities().then((nextEntities) => {
const nextLightEntityList = nextEntities.filter((ent) =>
ent.entity_id.startsWith('light.'),
);
setLightEntityList(nextLightEntityList);
// console.log(
// 'light entities',
// nextLightEntityList,
// );
const switchEntities = nextEntities.filter((ent) =>
ent.entity_id.includes('switch'),
);
// console.log('entities', switchEntities);
// Fill flattenedEntities with entity
flattenedEntities = flattenedEntities.map((item) => {
const entity = switchEntities.find(
(ent) => ent.entity_id === item.entityId,
);
return {
...item,
entity,
};
});
// console.log('flattenedEntities', flattenedEntities);
const MATCH_KEYS = [
// v8
'开关一键',
'开关二键',
'开关三键',
'开关四键',
// v5
'按键1',
'按键2',
'按键3',
'按键4',
];
flattenedEntities = flattenedEntities.filter((item) =>
MATCH_KEYS.some((key) =>
item?.entity?.attributes?.friendly_name?.includes(key),
),
);
// console.log('flattenedEntities', flattenedEntities);
const filledEntities: Record<string, EntityItem> =
flattenedEntities.reduce((acc: Record<string, EntityItem>, item) => {
acc[item.entityId] = item;
return acc;
}, {});
setEntities(filledEntities);
});
}, [devices]);
useEffect(() => {
// 将 entityList 数据设置到表单中
const keys = Object.keys(entities);
if (keys.length > 0) {
// 首先尝试从localStorage恢复数据
const savedData = localStorage.getItem('miBindMapper');
if (savedData) {
try {
const parsedData = JSON.parse(savedData);
// 只恢复knxItemId映射,保持entityId不变
const miEntities = keys.map((key) => ({
entityId: key,
knxItemId: parsedData[key] || undefined,
}));
form.setFieldsValue({ miEntities });
} catch (e) {
console.error('解析 localStorage 数据失败:', e);
// 如果解析失败,使用默认值
form.setFieldsValue({
miEntities: keys.map((key) => ({
entityId: key,
})),
});
}
} else {
// 没有保存的数据,使用默认值
form.setFieldsValue({
miEntities: keys.map((key) => ({
entityId: key,
})),
});
}
}
}, [entities, form]);
const selectOptions = useMemo(() => {
return lightEntityList.map((item) => ({
label: item.attributes.friendly_name,
value: item.entity_id,
}));
}, [lightEntityList]);
return (
<div>
<Alert
message={`灯具数量: ${lightEntityList.length},蓝牙模块数量: ${devices.length}(${Object.keys(entities).length}个按键)`}
type="info"
/>
{lightEntityList.length === 0 ? (
<div style={{ textAlign: 'center', padding: '20px' }}>
<Spin tip="加载中..." />
</div>
) : (
<Form
form={form}
layout="vertical"
onValuesChange={(_, values) => {
if (values.miEntities) {
// 只保存entityId到knxItemId的映射
const mapping: Record<string, string> = {};
values.miEntities.forEach(
(item: { entityId: string; knxItemId: string }) => {
if (item.entityId && item.knxItemId) {
mapping[item.entityId] = item.knxItemId;
}
},
);
localStorage.setItem('miBindMapper', JSON.stringify(mapping));
}
}}
>
<Form.List name="miEntities">
{(fields) => (
<>
{fields.map(({ key, name }) => (
<Flex key={key} vertical gap="small">
<Divider size="small" />
<Form.Item noStyle name={[name, 'entityId']}>
<Title entities={entities} />
</Form.Item>
<Form.Item noStyle name={[name, 'knxItemId']}>
<Select
options={selectOptions}
showSearch
optionFilterProp="label"
/>
</Form.Item>
</Flex>
))}
</>
)}
</Form.List>
{/* 生成脚本 */}
<Divider>automations.yaml</Divider>
<Alert
message="覆盖 automations.yaml(如果你自己编辑了自动化可以备份,没有就覆盖),重新加载配置即实现双向绑定"
type="info"
/>
<Form.Item noStyle shouldUpdate>
{() => {
const list = (
(form.getFieldValue('miEntities') || []) as {
entityId: string;
knxItemId: string;
}[]
).filter((item) => item.knxItemId);
return (
<Input.TextArea
value={batchGenScripts(entities, selectOptions, list)}
rows={10}
style={{ marginTop: 16 }}
/>
);
}}
</Form.Item>
</Form>
)}
</div>
);
};
export default MiBindEditorMapper;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/index.tsx
|
TypeScript (TSX)
|
import React, { JSX, useState } from 'react';
import { Card, Steps, Row, Col, Alert } from 'antd';
import { SettingOutlined, WifiOutlined } from '@ant-design/icons';
import KNXEditor from './KNXEditor';
import MiBindEditor from './MiBindEditor';
import { KNXItem } from './types';
function SetupPage(): JSX.Element {
const [currentStep, setCurrentStep] = useState(0);
const [knxList, setKnxList] = useState<KNXItem[]>([]);
const handleStepChange = (step: number) => {
setCurrentStep(step);
};
const handleKNXChange = (items: KNXItem[]) => {
console.log('KNX 数据更新:', items);
setKnxList(items);
};
const renderStepContent = () => {
switch (currentStep) {
case 0:
return <KNXEditor onKNXChange={handleKNXChange} />;
case 1:
return <MiBindEditor knxItems={knxList} />;
default:
return null;
}
};
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'flex-start',
minHeight: '100vh',
width: '100%',
padding: '20px',
}}
>
<Row gutter={32} style={{ width: '100%' }}>
<Col span={12}>
<Card title="系统设置向导">
<Alert
message="依次操作,点击可以切换当前步骤"
type="info"
style={{ marginBottom: 20 }}
/>
<Steps
direction="vertical"
current={currentStep}
onChange={handleStepChange}
items={[
{
icon: <SettingOutlined />,
title: '配置 KNX 开关',
description: '把开发商的开关接入 HA 盒子',
},
{
icon: <WifiOutlined />,
title: '配置小米设备',
description: '绑定小米智能设备和 KNX 开关的关系',
},
]}
/>
</Card>
</Col>
<Col span={12}>
<Card title="配置详情">{renderStepContent()}</Card>
</Col>
</Row>
</div>
);
}
export default SetupPage;
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/types.ts
|
TypeScript
|
export interface KNXItem {
name: string;
address: string;
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/SetupPage/util.ts
|
TypeScript
|
import { EntityItem } from './MiBindEditorMapper';
// KNX 开 -> 小米 开
export const OPEN_KNX_2_MI = `
- id: '【编号】'
alias: '【房间】 - open 【KNX设备ID】 2 【小米设备按键ID】'
description: ''
triggers:
- trigger: state
entity_id:
- 【KNX设备ID】
to: 'on'
conditions:
- condition: device
type: is_off
device_id: 【小米设备ID】
entity_id: 【小米设备按键ID】
domain: switch
actions:
- type: turn_on
device_id: 【小米设备ID】
entity_id: 【小米设备按键ID】
domain: switch
mode: single
`.trim();
// KNX 关 -> 小米 关
export const CLOSE_KNX_2_MI = `
- id: '【编号】'
alias: '【房间】 - close 【KNX设备ID】 2 【小米设备按键ID】'
description: ''
triggers:
- trigger: state
entity_id:
- 【KNX设备ID】
to: 'off'
conditions:
- condition: device
type: is_on
device_id: 【小米设备ID】
entity_id: 【小米设备按键ID】
domain: switch
actions:
- type: turn_off
device_id: 【小米设备ID】
entity_id: 【小米设备按键ID】
domain: switch
mode: single
`.trim();
// 小米 开 -> KNX 开
export const OPEN_MI_2_KNX = `
- id: '【编号】'
alias: '【房间】 - open 【小米设备按键ID】 2 【KNX设备ID】'
description: ''
triggers:
- type: turned_on
device_id: 【小米设备ID】
entity_id: 【小米设备按键ID】
domain: switch
trigger: device
conditions:
- condition: state
entity_id: 【KNX设备ID】
state: 'off'
actions:
- action: light.turn_on
metadata: {}
data: {}
target:
entity_id: 【KNX设备ID】
mode: single
`.trim();
// 小米 关 -> KNX 关
export const CLOSE_MI_2_KNX = `
- id: '【编号】'
alias: '【房间】 - close 【小米设备按键ID】 2 【KNX设备ID】'
description: ''
triggers:
- type: turned_off
device_id: 【小米设备ID】
entity_id: 【小米设备按键ID】
domain: switch
trigger: device
conditions:
- condition: state
entity_id: 【KNX设备ID】
state: 'on'
actions:
- action: light.turn_off
metadata: {}
data: {}
target:
entity_id: 【KNX设备ID】
mode: parallel
`.trim();
export const BATCH_SYNC = `
- id: '${Date.now() - 233}'
alias: resync all knx 2 mi
description: ""
triggers:
- trigger: homeassistant
event: start
conditions: []
actions:
- action: automation.turn_off
metadata: {}
data:
stop_actions: true
target:
label_id: mi_2_knx
- delay: "00:01:00"
- action: automation.turn_on
metadata: {}
data: {}
target:
label_id: sync
mode: single
`;
export const generateScript = (
template: string,
room: string,
knxId: string,
deviceId: string,
entityId: string,
idOffset: number,
now: number,
): string => {
const ret =
template
// 替换占位符
.replaceAll('【房间】', room)
.replaceAll('【编号】', (now + idOffset).toString())
.replaceAll('【小米设备ID】', deviceId)
.replaceAll('【小米设备按键ID】', entityId)
.replaceAll('【KNX设备ID】', knxId) + '\n';
return ret;
};
export const batchGenScripts = (
entities: Record<string, EntityItem>,
knxDescList: { label: string; value: string }[],
itemList: {
entityId: string;
knxItemId: string;
}[] = [],
) => {
const scripts: string[] = [];
let idOffset = 0;
const now = Date.now();
// Add the batch sync script
scripts.push(BATCH_SYNC);
itemList.forEach((item) => {
const entity = entities[item.entityId];
if (entity) {
const { entityId: miSwitchId, knxItemId: knxSwitchId } = item;
const {
deviceId: miDeviceId,
// deviceName: miDeviceName,
entity: { attributes: { friendly_name: miSwitchName } = {} } = {},
} = entity;
const knxName =
knxDescList.find((item) => item.value === knxSwitchId)?.label ||
'默认房间';
// 添加备注行,注明是哪个 KNX 和小米开关的
scripts.push(
`##### KNX: ${knxName} (${
knxSwitchId
}) -> 小米: ${miSwitchName || '默认房间'} (${
miDeviceId
} > ${miSwitchId})`,
);
scripts.push(
generateScript(
OPEN_KNX_2_MI,
knxName,
knxSwitchId,
miDeviceId,
miSwitchId,
idOffset++,
now,
),
generateScript(
CLOSE_KNX_2_MI,
knxName,
knxSwitchId,
miDeviceId,
miSwitchId,
idOffset++,
now,
),
generateScript(
OPEN_MI_2_KNX,
knxName,
knxSwitchId,
miDeviceId,
miSwitchId,
idOffset++,
now,
),
generateScript(
CLOSE_MI_2_KNX,
knxName,
knxSwitchId,
miDeviceId,
miSwitchId,
idOffset++,
now,
),
);
}
});
return scripts.join('\n');
};
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/home-assistant-js-websocket.d.ts
|
TypeScript
|
declare module 'home-assistant-js-websocket' {
export interface Auth {}
export type getAuth = (info?: { hassUrl?: string }) => Auth;
// HashCode: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkMGQ0OTg4Y2RmNWM0NmMwOWMxY2ExMDU4YWJiZmFkYiIsImlhdCI6MTc1ODAzNzY3MywiZXhwIjoyMDczMzk3NjczfQ.Y1YPIotO4CbLt7rJ7tHAaP9fCxIEGH9NoL0_1XRzyXo
}
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/index.tsx
|
TypeScript (TSX)
|
import { createRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('root') as HTMLElement;
const root = createRoot(container);
root.render(<App />);
// calling IPC exposed from preload script
window.electron?.ipcRenderer.once('ipc-example', (arg) => {
// eslint-disable-next-line no-console
console.log(arg);
});
window.electron?.ipcRenderer.sendMessage('ipc-example', ['ping']);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/preload.d.ts
|
TypeScript
|
import { ElectronHandler } from '../main/preload';
declare global {
// eslint-disable-next-line no-unused-vars
interface Window {
electron: ElectronHandler;
}
}
export {};
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
src/renderer/useHA.ts
|
TypeScript
|
import React from 'react';
/** A control of Home Assistant */
export interface Instance {
login: (host: string, token: string) => Promise<void>;
getDevices: () => Promise<HADevice[]>;
getEntities: () => Promise<HAEntity[]>;
}
export interface HAEntity {
entity_id: string;
state: string;
attributes: {
friendly_name: string;
};
}
/** Home Assistant Device */
export interface HADevice {
deviceId: string;
name: string;
entities: string[];
}
export default function useHA(): Instance {
const urlRef = React.useRef<{
host?: string;
token?: string;
}>({});
return React.useMemo<Instance>(() => {
const inst = {
login: async (host: string, token: string) => {
try {
const response = await fetch(`${host}/api/config`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (response.ok) {
const config = await response.json();
console.log('Home Assistant Config:', config);
urlRef.current = { host, token };
} else {
console.error(
'Failed to fetch Home Assistant config:',
response.status,
response.statusText,
);
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
} catch (error) {
console.error('Error fetching Home Assistant config:', error);
throw error;
}
},
getDevices: async () => {
const url = `${urlRef.current.host}/api/template`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${urlRef.current.token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template:
"{% set devices = states | map(attribute='entity_id') | map('device_id') | unique | reject('eq',None) | list %}{%- set ns = namespace(devices = []) %}{%- for device in devices %}{%- set entities = device_entities(device) | list %}{%- if entities %}{%- set ns.devices = ns.devices + [ {device: {'name': device_attr(device, 'name'), 'entities': entities}} ] %}{%- endif %}{%- endfor %}{{ ns.devices | tojson }}",
}),
});
if (response.ok) {
const devices = await response.json();
// console.log('Home Assistant Devices:', devices);
const deviceList = devices.map((obj: any) => {
const keys = Object.keys(obj);
const deviceId = keys[0];
const { name, entities, ...rest } = obj[deviceId];
return {
name,
entities,
deviceId,
...rest,
};
});
return deviceList;
} else {
console.error(
'Failed to fetch Home Assistant devices:',
response.status,
response.statusText,
);
return [];
}
} catch (error) {
console.error('Error fetching Home Assistant devices:', error);
return [];
}
},
getEntities: async () => {
const url = `${urlRef.current.host}/api/states`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${urlRef.current.token}`,
'Content-Type': 'application/json',
},
});
if (response.ok) {
const entities = await response.json();
return entities;
} else {
console.error(
'Failed to fetch Home Assistant entities:',
response.status,
response.statusText,
);
return [];
}
} catch (error) {
console.error('Error fetching Home Assistant entities:', error);
return [];
}
},
};
return inst;
}, []);
}
export const HAContext = React.createContext<Instance | undefined>(undefined);
|
zombieJ/jinding-ha
| 0
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
|
.eslintrc.js
|
JavaScript
|
const base = require('@umijs/fabric/dist/eslint');
module.exports = {
...base,
rules: {
...base.rules,
'no-template-curly-in-string': 0,
'prefer-promise-reject-errors': 0,
'react/no-array-index-key': 0,
'react/sort-comp': 0,
'@typescript-eslint/no-explicit-any': 0,
'import/no-extraneous-dependencies': 0,
'no-mixed-operators': 0,
},
};
|
zombieJ/malfurion
| 0
|
A svg control lib
|
TypeScript
|
zombieJ
|
二货爱吃白萝卜
|
alipay
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.