Add support for multiple shared preference files

Summary: Adds the ability to view multiple shared preference files in Flipper

Reviewed By: danielbuechele

Differential Revision: D10181908

fbshipit-source-id: 723b71d7bd87c51c0fabc77204b5a26a2b7aa782
This commit is contained in:
Hilal Alsibai
2018-10-06 11:31:39 -07:00
committed by Facebook Github Bot
parent 630982190b
commit b40810080c
2 changed files with 214 additions and 74 deletions

View File

@@ -17,12 +17,15 @@ import com.facebook.flipper.core.FlipperObject;
import com.facebook.flipper.core.FlipperPlugin; import com.facebook.flipper.core.FlipperPlugin;
import com.facebook.flipper.core.FlipperReceiver; import com.facebook.flipper.core.FlipperReceiver;
import com.facebook.flipper.core.FlipperResponder; import com.facebook.flipper.core.FlipperResponder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
public class SharedPreferencesFlipperPlugin implements FlipperPlugin { public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
private FlipperConnection mConnection; private FlipperConnection mConnection;
private final SharedPreferences mSharedPreferences; private final Map<SharedPreferences, SharedPreferencesDescriptor> mSharedPreferences;
private final SharedPreferences.OnSharedPreferenceChangeListener private final SharedPreferences.OnSharedPreferenceChangeListener
onSharedPreferenceChangeListener = onSharedPreferenceChangeListener =
new SharedPreferences.OnSharedPreferenceChangeListener() { new SharedPreferences.OnSharedPreferenceChangeListener() {
@@ -31,13 +34,18 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
if (mConnection == null) { if (mConnection == null) {
return; return;
} }
SharedPreferencesDescriptor descriptor = mSharedPreferences.get(sharedPreferences);
if (descriptor == null) {
return;
}
mConnection.send( mConnection.send(
"sharedPreferencesChange", "sharedPreferencesChange",
new FlipperObject.Builder() new FlipperObject.Builder()
.put("preferences", descriptor.name)
.put("name", key) .put("name", key)
.put("deleted", !mSharedPreferences.contains(key)) .put("deleted", !sharedPreferences.contains(key))
.put("time", System.currentTimeMillis()) .put("time", System.currentTimeMillis())
.put("value", mSharedPreferences.getAll().get(key)) .put("value", sharedPreferences.getAll().get(key))
.build()); .build());
} }
}; };
@@ -71,8 +79,26 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
* @param mode The Context mode to utilize. * @param mode The Context mode to utilize.
*/ */
public SharedPreferencesFlipperPlugin(Context context, String name, int mode) { public SharedPreferencesFlipperPlugin(Context context, String name, int mode) {
mSharedPreferences = context.getSharedPreferences(name, mode); this(context, Arrays.asList(new SharedPreferencesDescriptor(name, mode)));
mSharedPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener); }
/**
* Creates a {@link android.content.SharedPreferences} plugin for Flipper
*
* @param context The context to retrieve the preferences from.
* @param descriptors A list of {@link SharedPreferencesDescriptor}s
* that describe the list of preferences to retrieve.
*/
public SharedPreferencesFlipperPlugin(Context context, List<SharedPreferencesDescriptor> descriptors) {
if (context == null) {
throw new IllegalArgumentException("Given null context");
}
mSharedPreferences = new HashMap<>(descriptors.size());
for (SharedPreferencesDescriptor descriptor : descriptors) {
SharedPreferences preferences = context.getSharedPreferences(descriptor.name, descriptor.mode);
preferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
mSharedPreferences.put(preferences, descriptor);
}
} }
@Override @Override
@@ -80,15 +106,26 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
return "Preferences"; return "Preferences";
} }
private FlipperObject getSharedPreferencesObject() { private SharedPreferences getSharedPreferencesFor(String name) {
final FlipperObject.Builder builder = new FlipperObject.Builder(); for (Map.Entry<SharedPreferences, SharedPreferencesDescriptor> entry : mSharedPreferences.entrySet()) {
final Map<String, ?> map = mSharedPreferences.getAll(); if (entry.getValue().name.equals(name)) {
return entry.getKey();
}
}
throw new IllegalStateException("Unknown shared preferences " +name);
}
private FlipperObject getFlipperObjectFor(String name) {
return getFlipperObjectFor(getSharedPreferencesFor(name));
}
private FlipperObject getFlipperObjectFor(SharedPreferences sharedPreferences) {
FlipperObject.Builder builder = new FlipperObject.Builder();
Map<String, ?> map = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) { for (Map.Entry<String, ?> entry : map.entrySet()) {
final Object val = entry.getValue(); final Object val = entry.getValue();
builder.put(entry.getKey(), val); builder.put(entry.getKey(), val);
} }
return builder.build(); return builder.build();
} }
@@ -96,12 +133,28 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
public void onConnect(FlipperConnection connection) { public void onConnect(FlipperConnection connection) {
mConnection = connection; mConnection = connection;
connection.receive(
"getAllSharedPreferences",
new FlipperReceiver() {
@Override
public void onReceive(FlipperObject params, FlipperResponder responder) {
FlipperObject.Builder builder = new FlipperObject.Builder();
for (Map.Entry<SharedPreferences, SharedPreferencesDescriptor> entry : mSharedPreferences.entrySet()) {
builder.put(entry.getValue().name, getFlipperObjectFor(entry.getKey()));
}
responder.success(builder.build());
}
});
connection.receive( connection.receive(
"getSharedPreferences", "getSharedPreferences",
new FlipperReceiver() { new FlipperReceiver() {
@Override @Override
public void onReceive(FlipperObject params, FlipperResponder responder) { public void onReceive(FlipperObject params, FlipperResponder responder) {
responder.success(getSharedPreferencesObject()); String name = params.getString("name");
if (name != null) {
responder.success(getFlipperObjectFor(name));
}
} }
}); });
@@ -111,10 +164,11 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
@Override @Override
public void onReceive(FlipperObject params, FlipperResponder responder) public void onReceive(FlipperObject params, FlipperResponder responder)
throws IllegalArgumentException { throws IllegalArgumentException {
String sharedPreferencesName = params.getString("sharedPreferencesName");
String preferenceName = params.getString("preferenceName"); String preferenceName = params.getString("preferenceName");
Object originalValue = mSharedPreferences.getAll().get(preferenceName); SharedPreferences sharedPrefs = getSharedPreferencesFor(sharedPreferencesName);
SharedPreferences.Editor editor = mSharedPreferences.edit(); Object originalValue = sharedPrefs.getAll().get(preferenceName);
SharedPreferences.Editor editor = sharedPrefs.edit();
if (originalValue instanceof Boolean) { if (originalValue instanceof Boolean) {
editor.putBoolean(preferenceName, params.getBoolean("preferenceValue")); editor.putBoolean(preferenceName, params.getBoolean("preferenceValue"));
@@ -132,7 +186,7 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
editor.apply(); editor.apply();
responder.success(getSharedPreferencesObject()); responder.success(getFlipperObjectFor(sharedPreferencesName));
} }
}); });
} }
@@ -141,4 +195,17 @@ public class SharedPreferencesFlipperPlugin implements FlipperPlugin {
public void onDisconnect() { public void onDisconnect() {
mConnection = null; mConnection = null;
} }
public static class SharedPreferencesDescriptor {
public final String name;
public final int mode;
public SharedPreferencesDescriptor(String name, int mode) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Given null or empty name");
}
this.name = name;
this.mode = mode;
}
}
} }

View File

@@ -12,27 +12,38 @@ import {
FlexColumn, FlexColumn,
colors, colors,
FlexRow, FlexRow,
DataInspector, ManagedDataInspector,
styled, styled,
Select,
} from 'flipper'; } from 'flipper';
import {FlipperPlugin} from 'flipper'; import {FlipperPlugin} from 'flipper';
const {clone} = require('lodash'); const {clone} = require('lodash');
type SharedPreferencesChangeEvent = {| type SharedPreferencesChangeEvent = {|
preferences: string,
name: string, name: string,
time: number, time: number,
deleted: boolean, deleted: boolean,
value: string, value: string,
|}; |};
export type SharedPreferences = { export type SharedPreferences = {|
[name: string]: any, [name: string]: any,
|};
type SharedPreferencesEntry = {
preferences: SharedPreferences,
changesList: Array<SharedPreferencesChangeEvent>,
};
type SharedPreferencesMap = {
[name: string]: SharedPreferencesEntry,
}; };
type SharedPreferencesState = {| type SharedPreferencesState = {|
sharedPreferences: ?SharedPreferences, selectedPreferences: ?string,
changesList: Array<SharedPreferencesChangeEvent>, sharedPreferences: SharedPreferencesMap,
|}; |};
const CHANGELOG_COLUMNS = { const CHANGELOG_COLUMNS = {
@@ -58,12 +69,17 @@ const DELETED_LABEL = <Text color={colors.cherry}>Deleted</Text>;
const InspectorColumn = styled(FlexColumn)({ const InspectorColumn = styled(FlexColumn)({
flexGrow: 0.2, flexGrow: 0.2,
padding: '16px',
}); });
const ChangelogColumn = styled(FlexColumn)({ const ChangelogColumn = styled(FlexColumn)({
flexGrow: 0.8, flexGrow: 0.8,
padding: '16px', paddingLeft: '16px',
});
const RootColumn = styled(FlexColumn)({
paddingLeft: '16px',
paddingRight: '16px',
paddingTop: '16px',
}); });
export default class extends FlipperPlugin<SharedPreferencesState> { export default class extends FlipperPlugin<SharedPreferencesState> {
@@ -71,37 +87,59 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
static id = 'Preferences'; static id = 'Preferences';
state = { state = {
changesList: [], selectedPreferences: null,
sharedPreferences: null, sharedPreferences: {},
}; };
reducers = { reducers = {
UpdateSharedPreferences(state: SharedPreferencesState, results: Object) { UpdateSharedPreferences(state: SharedPreferencesState, results: Object) {
let update = results.update;
let entry = state.sharedPreferences[update.name] || {changesList: []};
entry.preferences = update.preferences;
state.sharedPreferences[update.name] = entry;
return { return {
changesList: state.changesList, selectedPreferences: state.selectedPreferences || update.name,
sharedPreferences: results.results, sharedPreferences: state.sharedPreferences,
}; };
}, },
ChangeSharedPreferences(state: SharedPreferencesState, event: Object) { ChangeSharedPreferences(state: SharedPreferencesState, event: Object) {
const sharedPreferences = {...(state.sharedPreferences || {})}; const change = event.change;
if (event.change.deleted) { const entry = state.sharedPreferences[change.preferences];
delete sharedPreferences[event.change.name]; if (entry == null) {
} else { return;
sharedPreferences[event.change.name] = event.change.value;
} }
if (change.deleted) {
delete entry.preferences[change.name];
} else {
entry.preferences[change.name] = change.value;
}
entry.changesList = [change, ...entry.changesList];
return { return {
changesList: [event.change, ...state.changesList], selectedPreferences: state.selectedPreferences,
sharedPreferences, sharedPreferences: state.sharedPreferences,
};
},
UpdateSelectedSharedPreferences(
state: SharedPreferencesState,
event: Object,
) {
return {
selectedPreferences: event.selected,
sharedPreferences: state.sharedPreferences,
}; };
}, },
}; };
init() { init() {
this.client this.client
.call('getSharedPreferences') .call('getAllSharedPreferences')
.then((results: SharedPreferences) => { .then((results: {[name: string]: SharedPreferences}) => {
this.dispatchAction({results, type: 'UpdateSharedPreferences'}); Object.entries(results).forEach(([name, prefs]) => {
const update = {name: name, preferences: prefs};
this.dispatchAction({update, type: 'UpdateSharedPreferences'});
});
}); });
this.client.subscribe( this.client.subscribe(
@@ -110,17 +148,19 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
this.dispatchAction({change, type: 'ChangeSharedPreferences'}); this.dispatchAction({change, type: 'ChangeSharedPreferences'});
}, },
); );
this.client.subscribe(
'newSharedPreferences',
(results: SharedPreferences) => {
this.dispatchAction({results, type: 'UpdateSharedPreferences'});
},
);
} }
onSharedPreferencesChanged = (path: Array<string>, value: any) => { onSharedPreferencesChanged = (path: Array<string>, value: any) => {
const values = this.state.sharedPreferences; const selectedPreferences = this.state.selectedPreferences;
if (selectedPreferences == null) {
return;
}
const entry = this.state.sharedPreferences[selectedPreferences];
if (entry == null) {
return;
}
const values = entry.preferences;
let newValue = value; let newValue = value;
if (path.length === 2 && values) { if (path.length === 2 && values) {
newValue = clone(values[path[0]]); newValue = clone(values[path[0]]);
@@ -128,25 +168,57 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
} }
this.client this.client
.call('setSharedPreference', { .call('setSharedPreference', {
sharedPreferencesName: this.state.selectedPreferences,
preferenceName: path[0], preferenceName: path[0],
preferenceValue: newValue, preferenceValue: newValue,
}) })
.then((results: SharedPreferences) => { .then((results: SharedPreferences) => {
this.dispatchAction({results, type: 'UpdateSharedPreferences'}); let update = {
name: this.state.selectedPreferences,
preferences: results,
};
this.dispatchAction({update, type: 'UpdateSharedPreferences'});
});
};
onSharedPreferencesSelected = (selected: string) => {
this.dispatchAction({
selected: selected,
type: 'UpdateSelectedSharedPreferences',
}); });
}; };
render() { render() {
if (this.state.sharedPreferences == null) { const selectedPreferences = this.state.selectedPreferences;
if (selectedPreferences == null) {
return null;
}
const entry = this.state.sharedPreferences[selectedPreferences];
if (entry == null) {
return null; return null;
} }
return ( return (
<RootColumn fill={true}>
<Heading>
<span style={{marginRight: '16px'}}>Preference File</span>
<Select
options={Object.keys(this.state.sharedPreferences).reduce(
(obj, item) => {
obj[item] = item;
return obj;
},
{},
)}
onChange={this.onSharedPreferencesSelected}
/>
</Heading>
<FlexRow fill={true} scrollable={true}> <FlexRow fill={true} scrollable={true}>
<InspectorColumn> <InspectorColumn>
<Heading>Inspector</Heading> <Heading>Inspector</Heading>
<DataInspector <ManagedDataInspector
data={this.state.sharedPreferences} data={entry.preferences}
setValue={this.onSharedPreferencesChanged} setValue={this.onSharedPreferencesChanged}
/> />
</InspectorColumn> </InspectorColumn>
@@ -156,7 +228,7 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
columnSizes={CHANGELOG_COLUMN_SIZES} columnSizes={CHANGELOG_COLUMN_SIZES}
columns={CHANGELOG_COLUMNS} columns={CHANGELOG_COLUMNS}
rowLineHeight={26} rowLineHeight={26}
rows={this.state.changesList.map((element, index) => { rows={entry.changesList.map((element, index) => {
return { return {
columns: { columns: {
event: { event: {
@@ -176,6 +248,7 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
/> />
</ChangelogColumn> </ChangelogColumn>
</FlexRow> </FlexRow>
</RootColumn>
); );
} }
} }